微信小程序上传图片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();

}

}

}

你可能感兴趣的:(微信小程序上传图片springboot接口)