文件上传

文件上传
环境搭建
添加文件上传依赖jar

        <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>

1.传统方式文件上传
编写文件上传页面upload.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传表单</title>
</head>
<body>

    <h3>传统方式文件上传</h3>
    <form action="/file/upload" method="post" enctype="multipart/form-data">
        文件描述:<input type="text" name="fileDescribe"><br>
        文件上传:<input type="file" name="file"><br>
        <input type="submit" value="开始上传">
    </form>
</body>
</html>

编写文件上传的控制层方法

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.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID;

/**
 * 传统方式文件上传
 */
@Controller
@RequestMapping("/file")
public class UploadController {

    /**
     * 传统方式文件上传
     * @param request  请求对象 包含文件上传信息
     * @param response
     * @throws Exception
     */
    @RequestMapping(path="/upload",method = RequestMethod.POST)
    public String upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //1. 获取文件的输出路径
        String path = "C:\\Users\\Administrator\\Desktop\\upload";
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }

        //2. 创建磁盘文件工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //3. 创建核心的解析类
        ServletFileUpload upload = new ServletFileUpload(factory);

        //4. 解析请求对象,获取到各个部分
        List<FileItem> fileItems = upload.parseRequest(request);

        //5. 遍历表单的各项
        for (FileItem fileItem : fileItems) {

            //6. 判断是普通项还是文件上传项
            if (fileItem.isFormField()) { // 普通项
                String name = fileItem.getFieldName(); //获取普通项name属性的值
                String value = fileItem.getString();   //获取普通项value属性的值
                System.out.println(name + "," + value);
            } else { //文件上传项
                String filename = fileItem.getName();//获取文件名称  a.txt
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid + "_" + filename;//唯一文件名
                fileItem.write(new File(path, filename));//完成文件上传
                fileItem.delete();//删除临时文件
            }
        }
        return "success";
    }
}

步骤总结

  1. 创建文件的输出路径String path = “C:\Users\Administrator\Desktop\upload”;

  2. 创建磁盘文件工厂DiskFileItemFactory factory = new DiskFileItemFactory();

  3. 创建核心的解析类 ServletFileUpload upload = new ServletFileUpload(factory);

  4. 解析文件上传的请求,获取文件上传的各个部分 List fileItems = upload.parseRequest(request);

  5. 遍历文件上传的各个部分,判断是一个文件上传项还是一个普通的表单项
    如果是一个文件上传项,获取文件名称和文件内容,使用write输出流将文件写到磁盘上
    如果是一个普通的表单项,获取name和value就可以了

6.注意:在执行传统上传文件的代码的时候,在springmvc.xml中不可以配置springmvc的上传文件的文件解析器配置,否则传统方式上传不了。

SpringMVC实现文件上传
在springmvc.xml中配置文件解析器

<!--
    配置文件上传解析器
    id的值是固定的
    class的值也是固定的
 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置上传文件的最大尺寸为5MB -->
    <property name="maxUploadSize" value="5242880" />
</bean>

编写文件上传页面

<h3>springmvc文件上传</h3>
    <form action="/springmvc/upload" method="post" enctype="multipart/form-data">
        文件描述:<input type="text" name="fileDescribe"><br>
        文件上传:<input type="file" name="file"><br>
        <input type="submit" value="开始上传">
    </form>

编写控制层代码

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * springmvc文件上传
 */
@Controller
@RequestMapping("/springmvc")
public class SpringmvcUploadController {

    /**
     * springmvc文件上传
     * @param file
     * @throws Exception
     */
    @RequestMapping(path="/upload",method = RequestMethod.POST)
    public String upload(MultipartFile file, String fileDescribe) throws Exception {
        //1. 获取文件的输出路径
        String path = "C:\\Users\\Administrator\\Desktop\\upload";
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }

        //2.获取文件名称
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "-" + filename;
        System.out.println(filename);
        System.out.println(fileDescribe);

        //3.上传
        file.transferTo(new File(path, filename));
        
        return "success";
    }
}

多文件上传
编写文件上传页面

<h3>springmvc多文件上传</h3>
    <form action="/multi/upload" method="post" enctype="multipart/form-data">
        文件描述:<input type="text" name="fileDescribe"><br>
        文件上传:<input type="file" name="files"><br>
        文件描述:<input type="text" name="fileDescribe"><br>
        文件上传:<input type="file" name="files"><br>
        <input type="submit" value="开始上传">
    </form>

编写控制层代码

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

/**
 * springmvc多文件上传
 */
@Controller
@RequestMapping("/multi")
public class MultiUploadController {

    /**
     * springmvc文件上传
     * @param files
     * @throws Exception
     */
    @RequestMapping(path="/upload",method = RequestMethod.POST)
    public String upload(MultipartFile[] files, String[] fileDescribe) throws Exception {
        //1. 获取文件的输出路径
        String path = "C:\\Users\\Administrator\\Desktop\\upload";
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }

        int i = 0;

        //2.获取文件名称
        for (MultipartFile file : files) {
            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            filename = uuid + "-" + filename;
            System.out.println(filename);
            System.out.println(fileDescribe[i]);
            i++;

            //3.上传
            file.transferTo(new File(path, filename));
        }

        return "success";
    }
}

跨服务器的文件上传
导入依赖jar包

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

修改文件服务器的web.xml

tomcat默认readonly为true,不支持跨服务器写入,需要修改为false

<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>
  <servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

上传页面

 <h3>springmvc跨服务器文件上传</h3>
    <form action="/cross/upload" method="post" enctype="multipart/form-data">
        文件描述:<input type="text" name="fileDescribe"><br>
        文件上传:<input type="file" name="file"><br>
        <input type="submit" value="开始上传">
    </form>

上传代码

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * springmvc跨服务器文件上传
 */
@Controller
@RequestMapping("/cross")
public class CrossUploadController {

    /**
     * springmvc跨服务器文件上传
     * @param file
     * @param fileDescribe
     * @return
     * @throws Exception
     */
    @RequestMapping(path="/upload",method = RequestMethod.POST)
    public String upload(MultipartFile file, String fileDescribe) throws Exception {
        //1. 获取文件服务器的输出路径
        String path = "http://localhost:9090/upload/";

        //2.获取文件名称
        String filename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "-" + filename;
        System.out.println(filename);
        System.out.println(fileDescribe);

        //3.上传
        //3.1获取jersey的client对象
        Client client = Client.create();
        //3.2获取服务器资源对象
        WebResource resource = client.resource(path + filename);
        //3.3完成上传
        resource.put(file.getBytes());

        return "success";
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值