首页 > 编程语言 > 详细

SpringMVC实现文件上传

时间:2021-02-28 21:57:06      阅读:36      评论:0      收藏:0      [点我收藏+]

SpringMVC实现文件上传

文件上传的必要前提

  1. form表单的enctype的取值必须是multipart/form-data

    默认值是application/x-www-form-urlencoded

  2. method的取值必须是post。

  3. 提供一个文件选择域<input type="file">

文件上传的原理

当form表单的enctype取值不是默认值后,request.getParameter()将失效。设置为默认值时,数据格式为key=value&key=value的格式。当form表单设置为multipart/form-data时,请求正文每一部分都是MIME类型描述的正文。

使用第三方组件实现文件上传

使用Commons-fileupload组件实现文件上传,需要导入该组件的支撑jar包:commons-io-2.4commons-fileupload-1.3.1

传统方式的文件上传

package com.example.controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/fileupload1")
    public String fileupload1(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("文件上传");
        //使用fileupload组件完成上传
        String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
        //判断该路径是否存在
        File file =new File(realPath);
        if(!file.exists()){
            System.out.println("文件");
            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(realPath,filename));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
    <form action="/user/fileupload1" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="upload"><br>
        <input type="submit" value="上传">
    </form>
</body>
</html>

springmvc方式上传文件

首先配置文件解析器,在springmvc.xml文件中

<!--配置文件解析器对象,要求id名必须是multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="10485760"/>
    <!--最大上传大小,单位是字节 10485760是10M-->
</bean>

注意,id是确定的。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>文件上传</title>
</head>
<body>
<form action="/file/fileupload2" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="upload"/><br>
    <input type="submit" value="上传">
</form>
</body>
</html>
package cn.example.Controller;
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 javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class fileController {
    @RequestMapping("/fileupload2")
    public String fileupload2(HttpServletRequest request, MultipartFile upload) throws IOException {
        //注意:MultipartFile参数名称必须和表单文件选择的input标签的name属性名相同。
        System.out.println("springmvc文件上传");
        String realPath = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(realPath);
        File file=new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        String filename = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-","");
        upload.transferTo(new File(realPath,filename));
        return "success";
    }
}

注意:方法的MultipartFile参数名称必须和表单文件选择的input标签的name属性名相同。

跨域问题

需要两个jar包:jersey-client-1.18.1.jarjersey-core-1.18.1.jar

package cn.itcast.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 fileuoload3(MultipartFile upload) throws Exception {
        System.out.println("跨服务器文件上传...");
        // 定义上传文件服务器路径
        String path = "http://localhost:9090/uploads/";
        // 说明上传文件项
        // 获取上传文件的名称
        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";
    }
}

文件下载

使用response

package cn.example.Controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class fileController {
    @RequestMapping("/filedownload")
    public String filedownLoad(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String filepath = "D:\\sources\\Java\\springmvc\\day02_springmvc_fileupload\\download\\";
        String filename = "abc.png";
        ServletOutputStream outputStream=response.getOutputStream();
        byte[] bytes= FileUtils.readFileToByteArray(new File(filepath,filename));
        response.setHeader("Content-Disposition","attchment;filename="+filename);
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
        return "success";
    }
}

推荐使用response方式,这种方式可以以json格式给前台返回提示信息。

使用ResponseEntity

package cn.example.Controller;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
@Controller
@RequestMapping("/file")
public class fileController {
	@RequestMapping("/filedownload2")
    public ResponseEntity<byte[]> download2() throws IOException {
        String filepath = "D:\\sources\\Java\\springmvc\\day02_springmvc_fileupload\\download\\";
        String filename = "abc.png";
        byte[] bytes=FileUtils.readFileToByteArray(new File(filepath,filename));
        HttpHeaders httpHeaders =new HttpHeaders();
        httpHeaders.set("Content-Disposition","attchment;filename="+filename);
        ResponseEntity<byte[]> entity=new ResponseEntity<>(bytes,httpHeaders, HttpStatus.OK);
        return entity;
    }
}

SpringMVC实现文件上传

原文:https://www.cnblogs.com/acknowledge/p/14460405.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!