springmvc文件传输

最近学习springmvc文件传输,踩了不少坑,记录一下

  1. 首先是同一服务器上的传输

controller:

@Controller
@RequestMapping("/user")
public class UserController {
    
    
    @RequestMapping("/fileupload")
    public String fileupload(MultipartFile pic, HttpServletRequest req) throws Exception{
    
    
        String path = req.getSession().getServletContext().getRealPath("/pic/");
        String filename = UUID.randomUUID().toString().replace("-", "") + "_" + pic.getOriginalFilename();
        File file = new File(path);
        if(!file.exists())
            file.mkdirs();
        pic.transferTo(new File(path, filename));
        req.setAttribute("filename", filename);
        return "success";
    }
}

注意MultipartFile的形参名称要和表单中的名称属性保持一致,这样springmvc才能够对其进行绑定

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

此外,文件解析器的beanId必须为“multipartResolver”

成功的话可以在target中看到传输上去的图片
在这里插入图片描述
在返回的成功页面使用<img src="<%=request.getContextPath() + "/pic/" + request.getAttribute("filename")%>">观察图片,结果显示不出来,报404,这是由于DispatcherServlet将静态资源拦截下来了,需要进行“放行”:

<mvc:resources mapping="/pic/**" location="/pic/"/>

最后访问成功

  1. 接着是跨服务器的传输

需要加入相对应的依赖:

<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-core</artifactId>
  <version>1.19.1</version>
</dependency>
<dependency>
  <groupId>com.sun.jersey</groupId>
  <artifactId>jersey-client</artifactId>
  <version>1.19.1</version>
</dependency>

controller:

@RequestMapping("/fileupload2")
    public String fileupload2(MultipartFile pic) throws Exception{
    
    
        String path = "http://localhost:9090/fileuploadserver_war_exploded/pic/";
        String filename = UUID.randomUUID().toString().replace("-", "") + "_" + pic.getOriginalFilename();
        Client client = Client.create();
        WebResource webResource = client.resource(path + filename);
        webResource.put(pic.getBytes());
        return "success";
    }

接着在目标服务器新建一个相对应的文件夹
在这里插入图片描述
否则会报409错误:

com.sun.jersey.api.client.UniformInterfaceException: PUT http://localhost:9090/fileuploadserver_war_exploded/pic/0e2cce5c20634d2b823a3040197a0478_IMG_7391.JPG returned a response status of 409 Conflict
	at ...

这里可能会出现405的错误,是由于服务器禁止其他服务器写入,需要修改tomcat的conf文件夹下的web.xml文件,在DefaultServlet中加入:

com.sun.jersey.api.client.UniformInterfaceException: PUT http://localhost:9090/fileuploadserver_war_exploded/pic/170409222a434885895b6870d63df9c9_IMG_7391.JPG returned a response status of 405 Method Not Allowed
	at ...
<init-param>
    <param-name>readOnly</param-name>
    <param-value>false</param-value>
</init-param>

完毕,执行成功
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40622253/article/details/108840104