// 文件上传相关代码
@PostMapping(value = "/upload")
@ResponseBody
public String upload(@RequestParam("file") List<MultipartFile> file) {
if (file.size()==0) {
return "文件为空";
}
for (int i = 0; i < file.size(); i++) {

// 获取文件名
String fileName = file.get(i).getOriginalFilename();
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
// 文件上传后的路径
String filePath = uploadpath;
// fileName = UUID.randomUUID() + suffixName;
UUID uuid = UUID.randomUUID();
String strUUID = uuid.toString().replaceAll("-", "");
//修改文件名,时间戳
LocalDateTime time = LocalDateTime.now();
String strTime = time.toString();
strTime = strTime.replaceAll("-", "").replaceAll("T", "").replaceAll(":", "");
File dest = new File(filePath + strUUID + fileName);
//File dest = new File(filePath + strTime + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
//一次只能传输一个文件
//file.get(i).transferTo(dest);
file.get(i).transferTo(dest);
//file.get(i).transferTo(dest);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

file.clear();
return "上传成功";
}
 <div>
        <a class="btn" title="添加附件" id="file_icon"><i class="icon-paper-clip"></i></a>
        <input type="file" id="file_add"  data-target="#file_icon" multiple="multiple"/>
      </div>function test(){
var formData = new FormData();
for (var i = 0; i< $('#file_add')[0].files.length; i++) {
formData.append('file', $('#file_add')[0].files[i]);
}
file_add_fun(formData);
};
function file_add_fun(formData){
$.ajax({

url: '/upload',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
}).fail(function(res) {});   
}哪位大神给讲解一下没步骤的原理,当我两次transferTo(dest)就抛异常了,文件找不到,是不是transferTo(dest)t 传输一次就关闭了?

解决方案 »

  1.   

    第二次使用transferTo(dest)因为临时文件夹里面的内容已经在第一次传输时删除了。所以报错。
      

  2.   

    看transferTo的javadoc,有这么一句:Transfer the received file to the given destination file. This may either move the file in the filesystem, copy the file in the filesystem, or save memory-held contents to the destination file. If the destination file already exists, it will be deleted first. If the file has been moved in the filesystem, this operation cannot be invoked again. Therefore, call this method just once to be able to work with any storage mechanism.