该接口首先通过Multipartfile得到前端上传的文件,然后将该文件写入磁盘中,我看了相关问题,但是我使用的确实是绝对路径,另外我是用Multipartfile.transferto()时,也报错Cannot write uploaded file to disk!
下面是出错接口代码
@PostMapping("/uploadFile/{recid}/{theme}/{extramsg}/{openid}")
public Result uploadFile(HttpServletRequest request, HttpServletResponse response,@PathVariable int recid,
@PathVariable String theme,@PathVariable String extramsg,@PathVariable String openid) throws Exception {
// System.out.println(recid);
// System.out.println(theme);
// System.out.println(extramsg);
// System.out.println(openid);
//判断用户输入是否合法
String userInputmsg = recid+theme+extramsg;
String checkres = msgSecCheck(userInputmsg);
if(checkres.equals("risky")) {//如果不合法,立即返回错误
return new Result(403,"出现错误:用户输入信息不合法" ,0,null);
}
RecFile recfile = new RecFile();
String name = null;
//获取文件需要上传到的路径
File directory = new File("D:\\微信上传文件test");
String path = directory.getCanonicalPath() + "\\upload\\";
// 判断存放上传文件的目录是否存在(不存在则创建)
File dir = new File(path);
if (!dir.exists()) {
dir.mkdir();
}
request.setCharacterEncoding("utf-8"); //设置编码
JSONArray jsonArray = new JSONArray();
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
Iterator<String> iterator = req.getFileNames();
while (iterator.hasNext()) {
HashMap<String, Object> res = new HashMap<String, Object>();
MultipartFile file = req.getFile(iterator.next());
// 获取文件名
String fileNames = file.getOriginalFilename();
System.out.println(fileNames);
// 如果是图片,进行图片合法性检测
String lastThree = fileNames.substring(fileNames.length()-3);
if(lastThree.equals("PNG")||lastThree.equals("png")||lastThree.equals("JEPG")||
lastThree.equals("jepg")||lastThree.equals("JPG")||lastThree.equals("jpg")||
lastThree.equals("gif")||lastThree.equals("GIF")){
//如果图片不合法
if(imgSecCheck(file).equals("risky")) {
return new Result(403,"出现错误:用户上传图片不合法 ",0,null);
}
}
if(fileNames.substring(0,4).equals("tmp_")) {//此处踩了一个大坑,pc端和手机端发送至后台的文件名格式是不一样的,需要分别进行判断和处理
//如果为手机端上传的文件
name = fileNames;
String destPath = path + name;
//真正写到磁盘上
File file1 = new File(destPath);
OutputStream out = new FileOutputStream(file1);
out.write(file.getBytes());
res.put("url", destPath);
// result.setValue(jsonArray);
jsonArray.add(res);
out.close();
}
else {//文件由pc端提交
System.out.println("进来没");
String temp[] = fileNames.split("\\.");
for(String s : temp) {
System.out.println(s);
}
//获取文件的唯一文件名
String uniqueName = temp[2];
//获取上传文件的后缀名
String extName = temp[3];
//组成新的文件名称
String newName = uniqueName + "." + extName;
name = newName;
System.out.println(newName);
String destPath = path + name;
//真正写到磁盘上
File file1 = new File(destPath);
OutputStream out = new FileOutputStream(file1.getAbsolutePath());
System.out.println(file1.getAbsolutePath());
System.out.println(destPath);
out.write(file.getBytes());
res.put("url", destPath);
// result.setValue(jsonArray);
jsonArray.add(res);
out.close();
}
}
}
报错截图: