当前位置: 首页 > 知识库问答 >
问题:

Spring:文件上传restfulweb服务

丌官霖
2023-03-14

我正在使用Spring4.0为RESTfulWeb服务创建POC。如果我们只传递字符串或任何其他基本数据类型,它就可以正常工作。

@RequestMapping(value="/upload/file", method=RequestMapping.post)
public String uploadFile(@RequestParam("fileName", required=false) String fileName){
    logger.info("initialization of object");
    //----------------------------------------

     System.out.Println("name of File : " + fileName);  

    //----------------------------------------
}

这个很好用。但如果我想将字节流或文件对象传递给函数,我如何编写具有这些参数的函数?我如何编写提供传递字节流的客户端?

@RequestMapping(value="/upload/file", method=RequestMapping.post)
public String uploadFile(@RequestParam("file", required=false) byte [] fileName){
     //---------------------
     // 
}

我尝试了这个代码,但是得到了415个错误。

@RequestMapping(value = "/upload/file", method = RequestMethod.POST, consumes="multipart/form-data")
public @ResponseBody String uploadFileContentFromBytes(@RequestBody MultipartFormDataInput input,  Model model) {
    logger.info("Get Content. "); 
  //------------
   }  

客户端代码-使用apache HttpClient

private static void executeClient() {
    HttpClient client = new DefaultHttpClient();
    HttpPost postReqeust = new HttpPost(SERVER_URI + "/file");

    try{
        // Set Various Attributes
        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("fileType" , new StringBody("DOCX"));

        FileBody fileBody = new FileBody(new File("D:\\demo.docx"), "application/octect-stream");
        // prepare payload
        multipartEntity.addPart("attachment", fileBody);

        //Set to request body
        postReqeust.setEntity(multipartEntity);

        HttpResponse response = client.execute(postReqeust) ;

        //Verify response if any
        if (response != null)
        {
            System.out.println(response.getStatusLine().getStatusCode());
        }

    }
    catch(Exception ex){
        ex.printStackTrace();
    }

共有2个答案

范承教
2023-03-14
<bean id="multipartResolver"
	class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
辛建业
2023-03-14

您可以创建如下所示的Rest服务。

@RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload( 
            @RequestParam("file") MultipartFile file){
            String name = "test11";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream = 
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

对于客户端,请执行以下操作。

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class Test {
  public static void main(String[] args) throws Exception {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost("http://localhost:8080/upload");
    File file = new File("C:\\Users\\Kamal\\Desktop\\PDFServlet1.pdf");

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "multipart/form-data");
    mpEntity.addPart("file", cbFile);


    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());
    if (resEntity != null) {
      System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
      resEntity.consumeContent();
    }

    httpclient.getConnectionManager().shutdown();
  }
}
 类似资料:
  • 在我的项目中,我在后端有Spring Boot,在前端有React.js。 我的后端工作正常,我知道,因为我已经用Postman测试过了。 在上传文件的前端,我有一个名为 ,它看起来像这样: 但问题是每次上传都失败。也许原因是路径,不确定。我试图路径。我得到的是C:\fakepath\Screenshot(187). png 现在我的问题是,如果是因为路径,我怎么才能正确地做它(据我所知,浏览器不

  • 主要内容:1. 编写 form 表单,2. 配置文件解析器(MultipartResolver ),3. 引入 Jar 包,4. 编写控制器方法,上传文件示例在实际的项目开发中,文件的上传和下载可以说是最常用的功能之一,例如图片的上传与下载、邮件附件的上传和下载等。本节我们将对 Spring MVC 中的文件上传功能进行讲解。 在 Spring MVC 中想要实现文件上传工作,需要的步骤如下。 1. 编写 form 表单 在 Spring MVC 项目中,大多数的文件上传功能都是通过 form

  • 上传文件是互联网中常常应用的场景之一,最典型的情况就是上传头像等,今天就带着带着大家做一个Spring Boot上传文件的小案例。 1、pom包配置 我们使用Spring Boot最新版本1.5.9、jdk使用1.8、tomcat8.0。 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-

  • 本文向大家介绍Spring Boot搭建文件上传服务的方法,包括了Spring Boot搭建文件上传服务的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例为大家分享了Spring Boot搭建文件上传服务的具体代码,供大家参考,具体内容如下 一、服务端 pom.xml 注意:spring-boot-starter-web 1.3.3.RELEASE 依赖的servlet是3.1 二、客户端

  • 问题内容: 我试图创建一个页面,允许用户选择要上传到我的SpringMVC Controller的文件。 这是我的控制器: 我的upload.html表单具有: 我也尝试过使用标准格式(非Thymeleaf格式): 不知道它是否相关,但是我有以下配置: 我的build.gradle中包含以下内容: 我正在运行嵌入式Tomcat,通过以下方式启动: 单击提交按钮时,在控制器中没有看到请求,但在浏览器

  • 我遵循这个指南: http://docs.spring.io/spring-security/site/docs/4.2.2.RELEASE/reference/htmlsingle/#csrf-multipartfilter? http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html#mvc-