图片上传功能在Controller层实现的完整方法如下:
方法一:
@RequestMapping("toUploadImage.do")
public String upload(@RequestParam MultipartFile uploadfile,
HttpServletRequest request, HttpServletResponse response,String tid) {
//获取输入的文件名
String fileName = uploadfile.getOriginalFilename();
if (StringUtils.isEmpty(fileName)) {
System.out.println("未上传文件名为空");
}
//获取路径
String tempPath = request.getSession().getServletContext().getRealPath("/")
+ "upload\\ysdwanimal";
File dir = new File(tempPath);
if (!tempPath.endsWith(File.separator)) {
tempPath = tempPath + File.separator;
}
if (!dir.exists()) {
dir.mkdirs();
}
System.out.println(tempPath+fileName);
//检查是否重复上传
HmImages hmImage = HmImageService.getEntryById(tid);
if(hmImage == null){
return "uploadfail";
}
//重写数据库储存路径
String lj=request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + "/whzhly/upload/ysdwanimal/"+id+".jpg";
//保存路径
ysdwAnimal.setLujing(lj);
ysdwAnimalService.saveOrUpdateYsdwAnimal(ysdwAnimal);
//获取完整的图片名
String newFile = tempPath + id+".jpg";
File file = new File(newFile);
//图片复制到指定文件夹中,实现路径
try {
FileCopyUtils.copy(uploadfile.getBytes(), file);
System.out.println("成功上传");
} catch (IOException e) {
e.printStackTrace();
return "uploadfail";
}
return "uploadsuccess";
}
方法二:
@RequestMapping("/toUpLoadHmImage.do")
public @ResponseBody String toUpLoadHmImage(HttpServletRequest request,
HttpServletResponse response,ModelMap model){
//获取到项目名称
String projectName = request.getContextPath();
//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
String savePath = request.getServletContext().getRealPath("/WEB-INF/primary/images");
File file = new File(savePath);
//判断上传文件的保存目录是否存在
if(!file.exists() && !file.isDirectory()){
//不存在,则创建目录
file.mkdir();
}
//消息提示
String message = "";
try {
DiskFileItemFactory factory = new DiskFileItemFactory();
//创建一个文件上传解析器
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
//设置上传的文件总的大小不能超过5M
upload.setSizeMax(1024 * 1024 * 5);
//判断提交上来的数据是否是上传表单的数据
if(!ServletFileUpload.isMultipartContent(request)){
return message;
}
/*
* 使用ServletFileUpload解析器解析上传数据,
* 解析结果返回的是一个List<FileItem>集合
*/
List<FileItem> list = upload.parseRequest(request);
for(FileItem item : list){
if(item.isFormField()){//如果fileitem中封装的是普通输入项的数据
String itemName = item.getFieldName();
String itemValue = item.getString("utf-8");
System.out.println(itemName + "=" + itemValue);
}else {//如果fileitem中封装的是上传文件
//得到上传的文件名称
String fileName =item.getName();
System.out.println("fileName=" + fileName);
if(fileName == null || fileName.trim().equals("")){
continue;
}
//处理获取到的上传文件的文件名的路径部分,只保留文件名部分
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
//获取item中的上传文件的输入流
InputStream inputStream = item.getInputStream();
//创建一个文件输出流
FileOutputStream outputStream = new FileOutputStream(savePath+"\\"+fileName);
//创建一个缓冲区
byte buffer[] = new byte[1024];
//判断输入流中的数据是否已经读完的标识
int len = 0;
//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
while((len=inputStream.read(buffer))>0){
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
outputStream.write(buffer, 0, len);
}
//关闭输入流
inputStream.close();
//关闭输出流
outputStream.close();
//删除处理文件上传时生成的临时文件
item.delete();
message = "文件上传成功";
}
}
} catch (Exception e) {
message= "文件上传失败!";
e.printStackTrace();
}
return message;
}