金石路545号水吧

微信小程序上传图片springboot接口带判断条件

2017-12-17  本文已影响30人  丁忠康

@Value("${jc.tmp.path}")    取出在application中配置的图片存储路径

privateStringlocalImgPath;  

/**

* InputStream,String,File相互转化

*@paramins

*@paramfile

*/

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);

}

}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();

}

}

}

//处理文件上传

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

@ResponseBody

publicString uploadImg(HttpServletRequest request)throwsException

{

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

InputStream in;

String a ="error";

//1.在缓存里有

if(image ==null)

{

MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

MultipartFile mfile = multipartRequest.getFile("file");

in = mfile.getInputStream();

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

System.out.println("webPath*****************"+ webPath);

String path =localImgPath+ mfile.getOriginalFilename();

System.out.println("save path:**************"+ path);

inputstreamtofile(in,newFile(path));

a = mfile.getOriginalFilename();

}else   //2.传上来的图片直接在流里有

{

in = image.getInputStream();

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

System.out.println("webPath*****************"+ webPath);

String path =localImgPath+ image.getSubmittedFileName();

System.out.println("save path:**************"+ path);

inputstreamtofile(in,newFile(path));

a = image.getSubmittedFileName();

}

//String[] names=a.split("\\.");

returna;

}

在application中定义 文件取出或保存的路径

jc.tmp.path=/home/cus/tmp/

上一篇 下一篇

猜你喜欢

热点阅读