我试图将图像发送到我的服务器以将其存储到mysql数据库。
我尝试使用jQuery发布Formdata并像java MultipartFile一样接收它并将其转换为bytes []。我找到了几种方法,但都没有工作, 请有人帮帮我吗?
这是我最好的尝试:
<form>
<input type="file" id="file"/>
<a onclick="uploadImage()" >Upload</a>
</form>
JS
function uploadImage() {
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
type : 'POST',
url : '/admin/uploadImage',
headers : {
"X-CSRF-TOKEN" : token
},
data : formData,
cache: false,
contentType: false,
processData: false,
});
alert("proso");
}
和JAVA
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public void save(@RequestParam("file") MultipartFile file)
{
try
{
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
System.out.println("file: " + convFile.getTotalSpace());
byte[] bFile = new byte[(int) convFile.length()];
FileInputStream fileInputStream = new FileInputStream(convFile);
fileInputStream.read(bFile);
fileInputStream.close();
Files newFile = new Files();
newFile.setFileName("4h");
newFile.setData(bFile);
filesRepository.save(newFile);
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
有人能帮助我吗?
答案 0 :(得分:0)
尝试以下代码
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public void save(MultipartHttpServletRequest request)
{
try
{
Iterator<String> itr = request.getFileNames();
while(itr.hasNext()) {
MultipartFile file = request.getFile(itr.next());
if(file != null) {
File convFile = new File(file.getOriginalFilename());
convFile.createNewFile();
System.out.println("file: " + convFile.getTotalSpace());
byte[] bFile = new byte[(int) convFile.length()];
FileInputStream fileInputStream = new
FileInputStream(convFile);
fileInputStream.read(bFile);
fileInputStream.close();
Files newFile = new Files();
newFile.setFileName("4h");
newFile.setData(bFile);
filesRepository.save(newFile);
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}