java,单文件和多文件上传代码范例
上传一个单文件,用request.getFile得到文件(下面的功能是上传到阿里云)
@RequestMapping(value = {"/content"}, method = RequestMethod.POST, headers = "content-type=multipart/form-data")
public String content(ModelMap modelMap,
MultipartHttpServletRequest request,
HttpServletResponse response){
response.setHeader("Access-Control-Allow-Origin", "*");
OSSUpload ossUpload = new OSSUpload("xinmeiti");
Iterator<String> itr = request.getFileNames();
MultipartFile file = request.getFile(itr.next());
Map<String, Object> map = new HashMap<>();
try{
byte[] bytes = org.apache.poi.util.IOUtils.toByteArray(file.getInputStream());
String fileType = getImageType(bytes);
String md5 = StringUtils.md5(String.valueOf(bytes));
String fileName = firstName +"/"+md5 + "."+ fileType;
Map<String, Object> uploadResult = ossUpload.upload(bytes, fileName);
if(!uploadResult.get("status").equals(0)){
modelMap.addAttribute("json", StringUtils.toJson(uploadResult));
}else{
map.put("url", cndName+fileName);
modelMap.addAttribute("json", StringUtils.toJson(map));
}
} catch (IOException e) {
modelMap.addAttribute("json", StringUtils.toJson(new ReturnMap(10004, "上传图片失败")));
e.printStackTrace();
}
return "mis/json";
}
上传多个文件,用request.getFile得到多文件
@RequestMapping(value = {"multipleFileUpload"}, method = {RequestMethod.GET, RequestMethod.POST})
public String multipleFileUpload(
ModelMap modelMap,
MultipartHttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "type") String type,
@RequestParam(value = "jobId") String jobId) throws IOException {
List < MultipartFile > files = request.getFiles("files");
response.setHeader("Access-Control-Allow-Origin", "http://www.gifmiao.com");
Map<String, Object> statusMap = new HashMap<>();
HttpSession session = request.getSession();
session.setAttribute("gifCompressStatus", statusMap);
int compressSize = getCompressSizeByValue(type);
for(MultipartFile file :files){
String filename = file.getOriginalFilename().split(".gif")[0];
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("size" , 0);
resultMap.put("status" , 0);
resultMap.put("url" , "");
statusMap.put(filename, resultMap);
InputStream is = file.getInputStream();
byte[] bytes = IOUtils.toByteArray(is);
CompressWorker worker = new CompressWorker(statusMap, bytes, filename, compressSize, jobId);
worker.start();
}
modelMap.addAttribute("json", StringUtils.toInsensitiveJson(new ReturnMap("线程已启动")));
return "json";
}
在使用MultipartHttpServletRequest类型的时候需要注意,随便什么request都是MultipartHttpServletRequest
在这里举两个可以用MultipartHttpServletRequest的例子。
后端代码:上传一个单文件
@RequestMapping(value = "/uploadInsight", method = RequestMethod.POST) public String uploadInsight(ModelMap modelMap, MultipartHttpServletRequest request, @RequestParam(value = "category") String category, @RequestParam(value = "title") String title, ) throws IOException{ Iterator<String> itr = request.getFileNames(); MultipartFile file = request.getFile(itr.next()); Map<String, Object> map = uploadImage(file); if(!map.get("state").equals("SUCCESS")){ modelMap.addAttribute("json", StringUtils.toJson(new ReturnMap(10004, "上传图片失败"))); return "mis/json"; } String fengmianImgUrl = (String) map.get("name"); InsightModel insightModel = new InsightModel(); insightModel.setCategory(category); insightModel.setThumbnail(fengmianImgUrl); insightModel.setTitle(title); datastore.save(insightModel); modelMap.addAttribute("json", StringUtils.toJson((new ReturnMap("OK")))); return "mis/json"; }
对应的前端代码可以是这样:(原生的js)
function upload(user){ //user是从表单里面接到的数据
var formData = new FormData();
formData.append("title", user.title);
formData.append("file", user.file);
formData.append("category", user.category);
var xhr = new XMLHttpRequest();
xhr.open('POST', "/editor/uploadInsight");
//xhr.withCredentials = true; //这个是关于跨域证书的
xhr.onload = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log("成功")
}
};
xhr.send(formData);
}
对应的前端代码也可以是这样:(jquery方式调用)
var formData = new FormData(); formData.append("file", file); formData.append("title", title); formData.append("category", category); $.ajax({ type : "POST", url : "/editor/uploadInsight", data : formData, processData : false, contentType : false , file:file, error: function(data) { }, success: function(data) { }, xhr: function() { } });

浙公网安备 33010602011771号