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

 更新时间:2021年10月1日 08:00  点击:1939

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>

如果遇到报错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服务器,此时不再报错。(注意要修改一下代码中的文件上传路径)

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

[!--infotagslink--]

相关文章

  • php无刷新利用iframe实现页面无刷新上传文件(1/2)

    利用form表单的target属性和iframe 一、上传文件的一个php教程方法。 该方法接受一个$file参数,该参数为从客户端获取的$_files变量,返回重新命名后的文件名,如果上传失...2016-11-25
  • 分享一段php获取linux服务器状态的代码

    简单的php获取linux服务器状态的代码,不多说-直接上函数:复制代码 代码如下:function get_used_status(){ $fp = popen('top -b -n 2 | grep -E "^(Cpu|Mem|Tasks)"',"r");//获取某一时刻系统cpu和内存使用情况 $rs =...2014-05-31
  • PHP判断上传文件类型的解决办法

    分享给大家php判断上传文件类型的方法,大家一起学习学习。/** * 读取文件前几个字节 判断文件类型 * @return String */ function checkTitle($filename){ $file=fopen($filename, "rb"); $bin=fread($file, 2); /...2015-10-21
  • Springboot+TCP监听服务器搭建过程图解

    这篇文章主要介绍了Springboot+TCP监听服务器搭建过程,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2020-10-28
  • 服务器 UDP端口占用几千个的解决办法

    前一段时间使用NetStat命令查看服务器端口时,发现服务器udp端口开放了好多,最少在1000个以上,当时事情比较多,没有管它,今天终于有点时间,仔细检查了一下,排除了这个问题. ...2016-01-27
  • PHP连接公司内部服务器的MYSQL数据库的简单实例

    “主机,用户名,密码”得到连接、“数据库,sql,连接”得到结果,最后是结果的处理显示。当然,数据库连接是扩展库为我们完成的,我们能做的仅仅是处理结果而已。...2013-09-29
  • 解决HttpPost+json请求---服务器中文乱码及其他问题

    这篇文章主要介绍了解决HttpPost+json请求---服务器中文乱码及其他问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-01-22
  • Vue使用formData格式类型上传文件的示例

    这篇文章主要介绍了Vue使用formData格式类型上传文件的示例代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下...2021-09-04
  • Hyper-V尝试连接到服务器出错无效类的解决方法

    这篇文章主要介绍了Hyper-V尝试连接到服务器出错无效类的解决方法,需要的朋友可以参考下...2016-09-28
  • mac使用Shell(终端)SSH连接远程服务器的方法

    这篇文章主要介绍了mac使用Shell(终端)SSH连接远程服务器的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-07-11
  • js实现上传图片到服务器

    这篇文章主要为大家详细介绍了js实现上传图片到服务器,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2021-04-11
  • c# HttpWebRequest通过代理服务器抓取网页内容应用介绍

    在C#项目开发过程中可能会有些特殊的需求比如:用HttpWebRequest通过代理服务器验证后抓取网页内容,要想实现此方法并不容易,本文整理了一下,有需求的朋友可以参考下...2020-06-25
  • c# FTP上传文件实例代码(简易版)

    下面小编就为大家分享一篇c# FTP上传文件的实例代码,超简单哦~希望对大家有所帮助。一起跟随小编过来看看吧,...2020-06-25
  • uploader秒传图片到服务器完整代码

    这篇文章主要为大家详细介绍了uploader秒传图片到服务器的完整代码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...2017-04-27
  • Linux环境下nginx搭建简易图片服务器

    这篇文章主要介绍了Linux环境下nginx搭建简易图片服务器,需要的朋友可以参考下...2016-01-27
  • Windows 2016 服务器安全设置

    最近公司的网站升级Windows 2016服务器,选择安装了最新版的Windows 2016,以前使用Windows服务器还是Windows 2003系统,发现变化还是挺多的,依次记录下来以备后面查阅...2020-10-05
  • 图文详解本地Windows 7/8上IIS服务器搭建教程

    这篇文章主要以图文结合的方式详细介绍了本地Windows 78上IIS服务器搭建教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下 ...2017-07-06
  • 使用node-media-server搭建一个简易的流媒体服务器

    这篇文章主要介绍了使用node-media-server搭建一个简易的流媒体服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-01-20
  • 阿里云免费套餐再次升级: 含云服务器、云数据库等35+产品

    阿里云免费套餐再次升级,提供更多产品,更久时长的使用,本次活动针对个人用户和企业用户,不过仅限新用户申请,想要了解更多,下面就来简单地了解一下活动规则 阿里云免费...2017-07-06
  • ECMall支持SSL连接邮件服务器的配置方法详解

    首先,主要是ecmall使用的phpmailer版本太低,不支持加密连接。然后,得对相应代码做一定调整。1. 覆盖phpmailer请从附件进行下载: 复制代码 代码如下:http://cywl.jb51.net:81/201405/yuanma/ecmall_phpmailer_lib(jb51.n...2014-05-31