转载http://www.zuidaima.com/blog/3509978829999104.htm
package com.sunflower.rm.web.domain.controller.manager;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Api(tags = "后台----文件上传")
@RestController
@RequestMapping("business")
public class FileUploadController {
private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);
/**
* 后台----文件上传
*
* @param request
* @return
*/
@ApiOperation("文件上传")
@PostMapping("/uplodeFile")
public JSONObject uplodeFile(HttpServletRequest request) throws Exception{
JSONObject jsonObject = new JSONObject();
long startTime = System.currentTimeMillis();
// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 检查form中是否有enctype="multipart/form-data"
if (request instanceof MultipartHttpServletRequest) {
// 将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next().toString());
if (file != null) {
//上传路径
String path = "D:/project/" + file.getOriginalFilename();
// 上传
file.transferTo(new File(path));
long endTime = System.currentTimeMillis();
System.out.println("上传所花时间:" + String.valueOf(endTime - startTime) + "ms");
jsonObject.put("code", 200);
jsonObject.put("message", "上传成功!");
jsonObject.put("path",path);
return jsonObject;
}else{
jsonObject.put("code", 400);
jsonObject.put("message", "上传失败,请稍后再试!");
return jsonObject;
}
}
}
jsonObject.put("code", 400);
jsonObject.put("message", "上传失败,请稍后再试!");
return jsonObject;
}
}
Java后台文件上传到服务器
最新推荐文章于 2024-10-05 10:46:42 发布