spring文件上传
package com.util;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;
@SuppressWarnings("Annotation")
public class UploadFile {
public static ResponseForm springUpload(HttpServletRequest request, String filePath, String reName) {
long startTime = System.currentTimeMillis();
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
Map<String, String> map = new HashMap<String, String>();
if (multipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
@SuppressWarnings("rawtypes")
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
MultipartFile file = multiRequest.getFile(iter.next().toString());
if (file != null) {
try {
String path;
if ("true".equals(reName)) {
String suffix = file.getOriginalFilename()
.substring(file.getOriginalFilename().lastIndexOf("."));
path = filePath + "/" + IDUtil.getLongID() + suffix;
} else {
path = filePath + "/" + file.getOriginalFilename();
}
file.transferTo(new File(path));
map.put(file.getOriginalFilename(), path);
} catch (IOException e) {
e.printStackTrace();
ResponseForm.errorResponse("上传出问题了!上传文件为:" + file.getOriginalFilename());
}
}
}
}
long endTime = System.currentTimeMillis();
System.out.println("上传用时:" + String.valueOf(endTime - startTime) + "ms");
return ResponseForm.successResponse(map);
}
}