簡體   English   中英

如何使用springMVC Restful Service和jQuery上傳文件

[英]how to upload a file with springMVC restful service and jQuery

我正在開發一個使用springMVC Restful服務作為后端服務,使用jQuery作為前端技術的應用程序。

現在,我需要將文件通過Web服務上載到服務器。 我不知道如何編寫這樣的文件上傳功能。 我應該如何通過jQuery將文件發送到服務器?

提前致謝。

我不確定您要的是什么,這是我從您那里得到的

像這樣的控制器代碼

map.put("a", "/Student_Photos/sample.jpg");

在jsp中寫你的東西,包括這個

<form:form modelAttribute="uploadItem" action="add" name="student"
                method="post" enctype="multipart/form-data"
                onSubmit="return validate();">

              <td width="152"  rowspan="4"  ><img id="blah"
                        src="<c:url value="${a}"/>" alt="your image" width="130"
                        height="110" />

                    <form:input path="fileData" id="image" type="file"
                            onchange="readURL(this)" /></td>
              </form:form>

在瀏覽器中有兩種主要方法:

  1. 對於現代瀏覽器,請使用HTML5 File API。 請參閱https://developer.mozilla.org/zh-CN/docs/Using_files_from_web_applications

  2. 如果需要支持舊的瀏覽器,則將文件發布到隱藏的iFrame中。 參見http://viralpatel.net/blogs/ajax-style-file-uploading-using-hidden-iframe/

在服務器端,我將假設您正在對REST servlet使用Spring Data REST(SDR)。 SDR不會上傳文件,但是您可以在同一Servlet中將SDR與常規的Spring MVC Dispatcher Servlet一起運行。

如果保存到數據庫,則MVC Dispatcher的FileController中的處理程序方法將如下所示:

@RequestMapping(value = "/files", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
@ResponseBody
List<FileEntity> upload(@RequestParam("file") MultipartFile[] multipartFiles) throws Exception {

    List<FileEntity> response = new ArrayList<FileEntity>();

    for (MultipartFile multipartFile : multipartFiles) {

        FileEntity f = new FileEntity(multipartFile.getBytes(), multipartFile.getContentType(), multipartFile.getOriginalFilename());

        fileRepository.save(f);

        response.add(f);

    }

    return response;

}

您需要在類路徑上使用SDR,Apache Commons FileUpload和IO(或使用更新的Servlet 3 API代替Apache Commons)。 將它們添加為Maven依賴項:

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.1</version>
    </dependency>

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-rest-webmvc</artifactId>
        <version>2.0.1.RELEASE</version>
    </dependency>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM