【问题标题】:How to send an ajax form with a file using FormData / Java如何使用 FormData / Java 发送带有文件的 ajax 表单
【发布时间】:2017-11-03 10:29:02
【问题描述】:

我正在尝试向服务器发送帖子,但我总是收到错误415我尝试了多种方法,但没有。

js:

var form = $('form')[0];
var formData = new FormData(form);
    $.ajax({
       method: "POST",
       url: "./signup",
       data: formData,
       enctype: 'multipart/form-data',
       cache: false,
       contentType: false,
       processData: false,
       success : function(data) {
           //...
       },
       error : function(qXHR, textStatus, errorThrown){
           console.log(errorThrown, "Error " + qXHR.status);
       }
    });

html:

<form id="signup-form" action="#">
  <div class="form-group">
    <label>First Name</label>
    <input name="firstName" type="text" id="firstName">
  </div>
  <div class="form-group">
    <label>Surname</label>
    <input name="surname" type="text" id="surname">
  </div>
  <div class="form-group">
    <label>File</label>
    <input type="file" name="attachFile" id="attachFile">
   </div>
 </div>
 <input type="submit" id="btn-submit-signup value="Submit">
</form>

java

//controller header
@RequestMapping(value = "/signup", headers = "content-type=multipart/*", method = RequestMethod.POST)
    public @ResponseBody Response<String> signup(@RequestBody UserSignup details) 



//UserSignup
public class UserSignup {
    private String firstName;
    private String surname;
    private MultipartFile attachFile;

    public UserSignup(){}

    //getters and setters...
}

知道有什么问题吗?

【问题讨论】:

  • 能否在浏览器中查看请求是否正确发送到服务器?
  • 好吧,我收到一个错误 415。之前工作得很好,因为我用这个调用发送了一个 json,现在我需要发送一个文件,所以我已经更改了代码以使用表单数据。 @SpringLearner
  • 你可以有另一个方法参数@RequestParam MultipartFile 文件并在你的ajax调用中提供一个数据类型

标签: javascript java ajax spring form-data


【解决方案1】:

Spring 有一个关于如何正确处理文件上传的指南:https://spring.io/guides/gs/uploading-files/

取自指南,这里是一个简单的例子

控制器

@Controller
public class FileUploadController {

    @PostMapping("/signup")
    public String handleFileUpload(@RequestParam("file") MultipartFile file,
            RedirectAttributes redirectAttributes) {
        storageService.store(file);
        redirectAttributes.addFlashAttribute("message",
            "You successfully uploaded " + file.getOriginalFilename() + "!");

        return "redirect:/";
    }
}

表格

<form id="signup-form" method="POST" enctype="multipart/form-data" action="/">
    <table>
        <tr><td>File to upload:</td><td><input type="file" name="file" /></td></tr>
        <tr><td></td><td><input type="submit" value="Upload" /></td></tr>
    </table>
</form>

阿贾克斯

$.post("./signup", $("#signup-form").serialize());

【讨论】:

    猜你喜欢
    • 2016-08-14
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多