java - 为什么spring不使用ajax上传呢?

标签 java jquery ajax spring

我正在尝试上传文件并希望保存在/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/

相关文章:

java - 我可以在使用 Cordova 的 iOS 应用程序中使用 Java 库吗?

java - 您将如何保存改造的列表响应

java - "non-concurrent multithreading"是否需要 volatile 关键字?

php - 努力用一个小的json和php来获取IP

javascript - 一页上有多个表单如何知道提交了哪一个表单

javascript - jquery ajax选项卡点击后更改为 "Loading..."

java - 使用代理的惰性一对一不起作用

Javascript数组值自动改变

javascript - 弹出窗口出现在错误的位置

javascript - 多页面环境下的PHP和JS