在我目前的spring-boot项目中,我有这个表单将war文件上传到服务器:
<form:war>
<div class="field-box">
<label th:text="${war}"></label>
<div class="col-md-7">
<input class="form-control arquivo" th:attr="data-classe=${command['class'].simpleName},target=${war}" th:id="${war}" type="file" />
</div>
</div>
</form:war>
表单由此控制器方法处理:
@RequestMapping(value="download", method=RequestMethod.GET)
@ResponseBody
public HttpEntity<byte[]> download(@RequestParam(value="id") String id) throws Exception {
return this.serv.download(id);
}
并在服务类中使用此方法:
public String upload(String id, String classe, String target, MultipartFile file) throws Exception {
Arquivo novo;
if(id == null) {
novo = new Arquivo(classe, target);
this.dao.insert(novo);
id = novo.getId();
} else {
novo = this.dao.findById(id);
}
byte[] bytes = file.getBytes();
File arquivo = new File(novo.toString());
if(!arquivo.exists())
if(arquivo.mkdirs())
arquivo.createNewFile();
BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(arquivo) );
stream.write(bytes);
stream.close();
return novo.getId();
}
所有这些都是由这个jquery代码触发的:
$("input.arquivo").on("change", function(event){
console.log('mudanca no campo de arquivo');
var c = $(this).data('classe');
var t = $(this).data('target');
var f = $(this).val();
$.ajax({
method: "POST",
url: "/Picture/upload",
data: { classe: c, target: t, file: f },
contentType: "multipart/form-data"
}).done(function(data){
console.log('id: '+data);
$(this).attr('type', 'hidden');
$(this).attr('name', t);
$(this).attr('value', data)
});
});
我的application.properties具有以下配置:
# Multipart Configuration
multipart.location = ${user.home}/.lojacms/Uploads
multipart.maxFileSize = 100Mb
multipart.maxRequestSize = 100Mb
multipart.fileSizeThreshold = 10Mb
但是当我尝试上传文件时,我收到上述错误(在标题中)。任何人都可以告诉我这里有什么问题?
答案 0 :(得分:0)
好的,然后我发现解决方案将javascript代码更改为:
$("input.arquivo").on("change", function(event){
var c = $(this).data('classe');
var t = $(this).data('target');
var formData = new FormData();
formData.append('classe', c);
formData.append('target', t);
formData.append('file', $('#input_'+t)[0].files[0]);
$.ajax({
method: "POST",
url: "/Arquivo/upload",
data: formData,
cache: false,
contentType: false,
processData: false
}).done(function(data){
$('#'+t).append('<input type="hidden" name="'+t+'" value="'+data+'"/>')
});
});
简而言之,我使用javascript的FormData
元素来处理提交给服务器的值,包括多部分数据。