java 图片上传
代碼是最有力量的,嘎嘎
@CrossOrigin
@ApiOperation(value = "上傳圖片", notes = "上傳圖片", httpMethod = "POST")
@ApiImplicitParam(name = "file", value = "圖片路徑", required = true, dataType = "file")
@ResponseBody
@PostMapping("/uploadImage")
public ResultSet uploadImage(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request)
throws IOException {
// 上傳的圖片只允許是 png 或者jpg 中的格式
if (file.getOriginalFilename().contains(".png") || file.getOriginalFilename().contains(".jpg")) {
// 根據(jù)相對(duì)路徑轉(zhuǎn)化為真實(shí)路徑
String rootpath = request.getSession().getServletContext().getRealPath(File.separator);// 獲得web應(yīng)用的絕對(duì)路徑
File createFile = new File(rootpath + "/image/");
if (!createFile.exists()) {// 判斷文件是否存在如果不存在則自動(dòng)創(chuàng)建文件夾
createFile.mkdir();
}
//String uuid = IdGen.uuid() + "_";// 隨機(jī)生成一個(gè)唯一性的id 確保apk文件重名
File f = new File(rootpath + "/image/" + file.getOriginalFilename());
if (f.exists()) {//上傳的文件已經(jīng)存在,則提示用戶重新上傳 apk 或者重命名
return ResultSet.getFail("文件已經(jīng)存在,請(qǐng)重新上傳或者重命名");
} else {
System.out.println(rootpath);
file.transferTo(f); // 將上傳的文件寫入到系統(tǒng)中
return ResultSet.getSuccess(rootpath +"/image/" + file.getOriginalFilename());
}
} else {
return ResultSet.getFail("上傳文件失敗");
}
}
另一種
@RequestMapping(value="/uploadPictures",method=RequestMethod.POST)
public Object uploadHeadPic(@RequestParam("file")CommonsMultipartFile file,InputStream inputStream,HttpServletRequest request) {
String uuid = UUID.randomUUID().toString().trim();
String fileN=file.getOriginalFilename();
int index=fileN.indexOf(".");
String fileName=uuid+fileN.substring(index);
try {
File fileMkdir=new File("F:\\photoTest");
if(!fileMkdir.exists()) {
fileMkdir.mkdir();
}
//定義輸出流 將文件保存在D盤 file.getOriginalFilename()為獲得文件的名字
FileOutputStream os = new FileOutputStream(fileMkdir.getPath()+"\\"+fileName);
InputStream in = file.getInputStream();
int b = 0;
while((b=in.read())!=-1){ //讀取文件
os.write(b);
}
os.flush(); //關(guān)閉流
in.close();
os.close();
} catch (Exception e) {
return Result.getFail("圖片上傳失敗);
}
return Result.getSuccess(fileN);
}
用到代碼的小伙伴給我點(diǎn)個(gè)贊呀
轉(zhuǎn)載于:https://www.cnblogs.com/shenhaha520/p/10484652.html
《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結(jié)
- 上一篇: css实用属性
- 下一篇: Asp.Net 将HTML中通过dom-