欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC跨服务器上传文件中出现405错误的解决

程序员文章站 2022-03-10 09:17:12
目录springmvc跨服务器上传文件中出现405错误springmvc跨服务器上传文件中出现405错误下面是 应用服务器 的代码package com.itheima.controller; imp...

springmvc跨服务器上传文件中出现405错误

下面是 应用服务器 的代码

package com.itheima.controller; 
import com.sun.jersey.api.client.client;
import com.sun.jersey.api.client.webresource;
import org.apache.commons.fileupload.fileitem;
import org.apache.commons.fileupload.disk.diskfileitemfactory;
import org.apache.commons.fileupload.servlet.servletfileupload;
import org.springframework.stereotype.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.multipart.multipartfile; 
import javax.servlet.http.httpservletrequest;
import java.io.file;
import java.util.list;
import java.util.uuid;
 
@controller
@requestmapping("/user")
public class usercontroller { 
    @requestmapping("/fileupload3")
    public string fileupload3(multipartfile upload) throws exception{
        system.out.println("跨服务器文件上传....");
 
        //定义上传文件服务器的路径
        string path = "http://localhost:9090/uploads/";
        system.out.println(upload.getbytes());
 
        //定义上传文件项
        //获取上传文件的名称
        string filename = upload.getoriginalfilename();
        //把文件的名称设置成唯一值,uuid
        string uuid = uuid.randomuuid().tostring().replace("-","");
        filename = uuid + "_" + filename;
 
        //创建客户端对象
        client client = client.create();
 
        //和图片服务器进行连接
        webresource webresource = client.resource(path + filename);  //相当于创建一个连接对象
 
        //上传文件按
        webresource.put(upload.getbytes()); 
        return "success";
    }
 
    /**
     * springmvc文件上传
     * @return
     */
    @requestmapping("/fileupload2")
    public string fileuoload2(httpservletrequest request, multipartfile upload) throws exception {
        system.out.println("springmvc文件上传...");
 
        // 使用fileupload组件完成文件上传
        // 上传的位置
        string path = request.getsession().getservletcontext().getrealpath("/uploads/");
        // 判断,该路径是否存在
        file file = new file(path);
        if(!file.exists()){
            // 创建该文件夹
            file.mkdirs();
        }
 
        // 说明上传文件项
        // 获取上传文件的名称
        string filename = upload.getoriginalfilename();
        // 把文件的名称设置唯一值,uuid
        string uuid = uuid.randomuuid().tostring().replace("-", "");
        filename = uuid+"_"+filename;
        // 完成文件上传
        upload.transferto(new file(path,filename)); 
        return "success";
    }
 
    /**
     * 文件上传
     * @return
     */
    @requestmapping("/fileupload1")
    public string fileuoload1(httpservletrequest request) throws exception {
        system.out.println("文件上传...");
 
        // 使用fileupload组件完成文件上传
        // 上传的位置
        string path = request.getsession().getservletcontext().getrealpath("/uploads/");
        // 判断,该路径是否存在
        file file = new file(path);
        if(!file.exists()){
            // 创建该文件夹
            file.mkdirs();
        }
 
        // 解析request对象,获取上传文件项
        diskfileitemfactory factory = new diskfileitemfactory();
        servletfileupload upload = new servletfileupload(factory);
        // 解析request
        list<fileitem> items = upload.parserequest(request);
        // 遍历
        for(fileitem item:items){
            // 进行判断,当前item对象是否是上传文件项
            if(item.isformfield()){
                // 说明普通表单向
            }else{
                // 说明上传文件项
                // 获取上传文件的名称
                string filename = item.getname();
                // 把文件的名称设置唯一值,uuid
                string uuid = uuid.randomuuid().tostring().replace("-", "");
                filename = uuid+"_"+filename;
                // 完成文件上传
                item.write(new file(path,filename));
                // 删除临时文件
                item.delete();
            }
        } 
        return "success";
    } 
}

springmvc.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
       xsi:schemalocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
 
    <!-- 开启注解扫描 -->
    <context:component-scan base-package="com.itheima"/>
 
    <!-- 视图解析器对象 -->
    <bean id="internalresourceviewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver">
        <property name="prefix" value="/web-inf/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
 
    <!--前端控制器,哪些静态资源不拦截-->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
 
    <!--前端控制器,哪些静态资源不拦截-->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
 
    <!--配置文件解析器对象-->
    <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver">
        <property name="maxuploadsize" value="10485760" />
    </bean>
 
    <!-- 开启springmvc框架注解的支持 -->
    <mvc:annotation-driven />
 
</beans>

success.jsp

<%--
created by intellij idea.
user: administrator
date: 2018/5/4
time: 21:58
to change this template use file | settings | file templates.
--%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
<title>title</title>
</head>
<body>
<h3>上传文件成功</h3>
</body>
</html>

web.xml

<?xml version="1.0" encoding="utf-8"?>
<!--
  licensed to the apache software foundation (asf) under one or more
  contributor license agreements.  see the notice file distributed with
  this work for additional information regarding copyright ownership.
  the asf licenses this file to you under the apache license, version 2.0
  (the "license"); you may not use this file except in compliance with
  the license.  you may obtain a copy of the license at
      http://www.apache.org/licenses/license-2.0
  unless required by applicable law or agreed to in writing, software
  distributed under the license is distributed on an "as is" basis,
  without warranties or conditions of any kind, either express or implied.
  see the license for the specific language governing permissions and
  limitations under the license.
-->
 
<!--
  - this is the cocoon web-app configurations file
  -
  - $id$
  -->
<!--suppress all -->
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
         xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 
  <display-name>archetype created web application</display-name>
 
  <servlet>
    <servlet-name>dispatcherservlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
    <init-param>
      <param-name>contextconfiglocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispatcherservlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
 
  <servlet>
    <servlet-name>default</servlet-name>
    <servlet-class>org.apache.catalina.servlets.defaultservlet</servlet-class>
    <init-param>
      <param-name>debug</param-name>
      <param-value>0</param-value>
    </init-param>
    <init-param>
      <param-name>listings</param-name>
      <param-value>true</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <!--配置解决中文乱码的过滤器-->
  <filter>
    <filter-name>characterencodingfilter</filter-name>
    <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>utf-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterencodingfilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

index.jsp

<%--
created by intellij idea.
user: qhc
date: 2019/10/9
time: 13:49
to change this template use file | settings | file templates.
--%>
<%@ page contenttype="text/html;charset=utf-8" language="java" %>
<html>
<head>
<title>文件上传</title>
</head>
<body>
<%--不知道为啥,在台式机可以跑成功,在笔记本就报错,难道是tomcat的版本的原因?--%>
<h3>传统文件上传</h3>
<form action="/user/fileupload1" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br>
<input type="submit" value="上传"/>
</form>
<h3>springmvc文件上传</h3>
<form action="/user/fileupload2" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload"/><br>
<input type="submit" value="上传"/>
</form>
<h3>跨服务器上传文件</h3>
<form action="/user/fileupload3" method="post" enctype="multipart/form-data">
选择文件:<input type="file" name="upload" /><br/>
<input type="submit" value="上传" />
</form>
<a href="/user/testgetrealpath" rel="external nofollow" >查看request.getsession().getservletcontext().getrealpath("\uploads\")的值</a>
</body>
</html>

SpringMVC跨服务器上传文件中出现405错误的解决

如果遇到报错405,put http://localhost:9090/uploads/.........

只需要在文件服务器中的 web.xml 中加入下面的代码

<servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.defaultservlet</servlet-class>
        <init-param>
            <param-name>debug</param-name>
            <param-value>0</param-value>
        </init-param>
        <init-param>
            <param-name>readonly</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>listings</param-name>
            <param-value>false</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

重点来了~

idea中springmvc跨服务器上传文件报405错误,修改了web.xml一样报错

这个问题是因为你使用的文件服务器的tomcat使用的是exploded模式部署,修改的tomcat本地conf下的web.xml对exploded的项目没有生效,此时应该使用war包模式进行部署,本地修改的web.xml文件继续保持修改状态,并且修改application context不为/,可以修改为:/+任意文件名

然后再重新部署一下tomcat服务器,此时不再报错。(注意要修改一下代码中的文件上传路径)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。