微信小程序上传图片springboot接口

一:在idea项目中创建IndexController,

//处理文件上传

@RequestMapping(value ="/uploadimg", method = RequestMethod.POST, consumes ="multipart/form-data")

@ResponseBody

publicString uploadImg(HttpServletRequest request)throws Exception

{

1.获取文件请求过来的图片

ApplicationPart image = (ApplicationPart) request.getPart("file");

2.获得图片的输入流

InputStream in = image.getInputStream();

3.获得项目路径

String webPath = request.getServletContext().getRealPath("/");

4.获得文件路径

String path = webPath +"imgupload\\"+ image.getSubmittedFileName();

5.把文件流转成文件

inputstreamtofile(in,newFile(path));

6.文件名切割

String[] names=image.getSubmittedFileName().split(".");

//返回json

returnnames[0];

}

//InputStream,String,File相互转化

private voidinputstreamtofile(InputStream ins, File file)

{

OutputStream os =null;

try

{

os =newFileOutputStream(file);

intbytesRead =0;

byte[] buffer =new byte[8192];

while((bytesRead = ins.read(buffer,0,8192)) != -1)

{

os.write(buffer,0, bytesRead);

}

System.out.println("inputstreamtofile");

}catch(FileNotFoundException e)

{

e.printStackTrace();

}catch(IOException e)

{

e.printStackTrace();

}finally

{

try

{

if(os !=null)

{

os.close();

}

if(ins !=null)

{

ins.close();

}

}catch(IOException e)

{

e.printStackTrace();

}

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • @Value("${jc.tmp.path}") 取出在application中配置的图片存储路径 privat...
    丁忠康阅读 870评论 0 0
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,719评论 0 17
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,834评论 18 399
  • 一、流的概念和作用。 流是一种有顺序的,有起点和终点的字节集合,是对数据传输的总成或抽象。即数据在两设备之间的传输...
    布鲁斯不吐丝阅读 10,137评论 2 95
  • 毛姆在《刀锋》里说,“世间万事万物都有个完,我们除非是傻子,才要求事物永久不变,但是,如果我们不抓着手里的东西及时...
    菠萝精灵阅读 197评论 0 0