春季使用ajax jquery上传图片,无需表单提交

Sri*_*ini 1 java jquery spring image-uploading jquery-file-upload

我在 Spring java 中做项目。需要在不使用表单提交的情况下上传图像并仅使用 jquery 的 ajax 调用(因为我需要在同一页面中处理图像)

我有type=file 的输入标签和

我已经在 spring maven 中加载了commons-fileupload、commons-io jar并且还添加了multipartResolver

现在我正在为 servlet 使用以下代码

@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> upload(@RequestParam("file") MultipartFile file) {
    Map<String, Object> map = Maps.newHashMap();
    try {
    BufferedImage src = ImageIO.read(new ByteArrayInputStream(file.getBytes()));
    File destination = new File("C:/Users/XXX/Desktop/Image_files/Image1.png");
    ImageIO.write(src, "png", destination);
    } catch(Exception e) {
        e.printStackTrace();
    }
    return map;
}
Run Code Online (Sandbox Code Playgroud)

我的js文件

$("#uploadbutton").on("click", function() {
var oMyForm = new FormData();
oMyForm.append("file", $("#imageid").prop("files")[0]);
$.ajax({
    url: "/photo/upload/upload",
    data: oMyForm,
    processData: false,
    contentType: false,
    type: 'POST',
    success: function(response) {
        alert("success");
    },
    error: function() {
        alert("unable to create the record");
    }
});
Run Code Online (Sandbox Code Playgroud)

});

问题是我可以在 input type=file 标签中选择图像,但是当我单击上传按钮时,onclick 事件触发并且不进行 ajax 调用,显示错误消息“405 方法不允许”,请帮我好吗? ?? 热切等待正面答复....任何其他方式也热烈欢迎

The*_*int 5

这里有几件事。查看您的实际 HTML 表单声明会很有帮助,包括#imageid 输入的“名称”和“接受”属性。它应该是这样的:

<form id="uploadForm">
     <input type="file" name="myimage" id="imageid" accept=".png" />
</form>
Run Code Online (Sandbox Code Playgroud)

其次,在您的 Ajax 调用中,声明返回数据类型总是一个好主意。在该调用旁边,在上传任何类型的文件时,您应该始终将缓存设置为 false。

因此,您的声明应如下所示:

$("#uploadbutton").on("click", function() {
var formData = new FormData($('#uploadForm')[0]);
$.ajax({
    url: "/photo/upload/upload",
    type: "POST",
    dataType: 'text',
    contentType: false,
    processData: false,
    cache: false,
    data: formData,
    success: function(response) {
        alert("success");
    },
    error: function() {
        alert("unable to create the record");
    }
});
Run Code Online (Sandbox Code Playgroud)

在这种情况下,您的控制器方法声明将是:

public Map<String, Object> upload(@RequestParam("myimage") MultipartFile file) {
     //rest of the code goes here...
}
Run Code Online (Sandbox Code Playgroud)

最后,您的 CommonsMultipartResolver 声明在您的 Spring MVC XML 文件中是什么样子的?它应该是这样的:

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="500000"/>

</bean>
Run Code Online (Sandbox Code Playgroud)