我正在尝试上传文件并希望保存在/resources/images 文件夹中。这是我的 Controller : RestController.java
@Controller
//@RequestMapping("/cont")
public class RestController {
@RequestMapping(value = "/echofile", method = RequestMethod.POST)
public @ResponseBody HashMap<String, Object> echoFile(MultipartHttpServletRequest request,
HttpServletResponse response) throws Exception {
MultipartFile multipartFile = request.getFile("file");
Long size = multipartFile.getSize();
String contentType = multipartFile.getContentType();
InputStream stream = multipartFile.getInputStream();
byte[] bytes = IOUtils.toByteArray(stream);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("fileoriginalsize", size);
map.put("contenttype", contentType);
map.put("base64", new String(Base64Utils.encode(bytes)));
return map;
}
我的index.jsp是:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC - Upload File</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
var isJpg = function(name) {
return name.match(/jpg$/i)
};
var isPng = function(name) {
return name.match(/png$/i)
};
$(document).ready(function() {
var file = $('[name="file"]');
var imgContainer = $('#imgContainer');
$('#btnUpload').on('click', function() {
var filename = $.trim(file.val());
if (!(isJpg(filename) || isPng(filename))) {
alert('Please browse a JPG/PNG file to upload ...');
return;
}
$.ajax({
url: "http://localhost:8080/SimpleAjaxJqueryPicUpload/api/echofile",
type: "POST",
data: document.getElementById("image"),
enctype: 'multipart/form-data',
processData: false,
contentType: false
}).done(function(data) {
imgContainer.html('');
var img = '<img src="data:' + data.contenttype + ';base64,'
+ data.base64 + '"/>';
imgContainer.append(img);
}).fail(function(jqXHR, textStatus) {
//alert(jqXHR.responseText);
alert('File upload failed ...');
});
});
$('#btnClear').on('click', function() {
imgContainer.html('');
file.val('');
});
});
</script>
</head>
<body>
<body style="font-family: calibri; font-size: 8pt">
<div>
<div id="fileForm">
<input type="file" name="file" id="image"/>
<button id="btnUpload" type="button">Upload file</button>
<button id="btnClear" type="button">Clear</button>
</div>
<div id="imgContainer"></div>
</div>
</body>
</html>
但是文件没有上传。当我单击该按钮时,它显示上传失败警报。怎么解决呢?
最佳答案
请包含这些行:
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
data: formData
您的 AJAX 代码如下所示 -
var formData = new FormData();
formData.append('file', jQuery('input[type=file]')[0].files[0]);
jQuery.ajax({
url: 'path',
type: "POST", // Type of request to be send, called as method
data: formData, // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response){
alert(response);
}
})
关于java - 为什么spring不使用ajax上传呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41275851/