vue+springboot文件上传
//vue element-ui组件
//js方法
//后台
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class UploadFile {
private static Logger log = LoggerFactory.getLogger(UploadFile.class);
@RequestMapping(value = "/upLoadFile", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
@ResponseBody
public String importFile(@RequestParam("file") MultipartFile file,
HttpServletRequest request){
log.info("importFile()");
Map<String, String> reMap = new HashMap<>();
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
log.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
log.info("上传的后缀名为:" + suffixName);
// 文件上传路径 应该改为服务器路径
String filePath = "f:/objdocument/";
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
reMap.put("msg", "上传成功");
} catch (IllegalStateException e) {
log.info(e.toString());
reMap.put("msg", "上传失败");
} catch (IOException e) {
log.info(e.toString());
reMap.put("msg", "上传失败");
}
String str = JsonUtil.map2Json(reMap);
return str;
}
}
application.properties相关配置
spring.http.multipart.enabled=true #默认支持文件上传.
spring.http.multipart.file-size-threshold=0 #支持文件写入磁盘.
spring.http.multipart.location= # 上传文件的临时目录
spring.http.multipart.max-file-size=1Mb # 最大支持文件大小
spring.http.multipart.max-request-size=10Mb # 最大支持请求大小