spring mvc 文件上传 - 2018
原创    java_world    发表于:2018-04-26 15:09:59
  阅读 :636   收藏   编辑

依赖

<dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
</dependency>


    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.2</version>
    </dependency>

具体可以参考 教你一步步搭建ssm框架,第一步实现springmvc下的页面跳转 - 2018

uploadFile.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title> spring mvc 文件上传</title>
</head>
<body>
    <form action="execUpload" method="post" enctype="multipart/form-data">
        fileName:<input type="text" name="fileName"/><br/>
        file:<input type="file" name="file"><br/>
        <input type="submit" value="上传">
    </form>
</body>
</html>

UploadController

package com.faceghost.app.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

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

@Controller
public class UploadController {

    /**
     * 文件上传
     * @param request
     * @return
     */
    @RequestMapping("/execUpload")
    public void execUpload(MultipartFile file , String fileName, HttpServletRequest request) throws Exception {
        //开始
        System.err.println("upload s ...");

        System.err.println("fileName:" + fileName);

        String oFileName = file.getOriginalFilename();

        System.err.println("oFileName:" + oFileName);

        /**
         * 获取文件类型
         * 
         */
        String fileType = oFileName.substring(oFileName.lastIndexOf("."),oFileName.length());

        /**
         * 获取项目webapp目录下的upload的路径
         */
        String prePath  = request.getSession().getServletContext().getRealPath("upload");

        System.err.println("prePath:" + prePath);

        /**
         * 上传保存后新的文件名称
         */
        String newFileName = UUID.randomUUID().toString() + fileType;

        System.err.println("newFileName:" + newFileName);



        /**
         * 复制流,或者,IOUtils.copy(input, output);
         */
        InputStream inputStream = file.getInputStream();
        File newFile = new File(prePath + File.separator + newFileName);

        OutputStream outputStream = new FileOutputStream(newFile);
        byte[] b = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(b)) > 0){
            outputStream.write(b,0,len);
        }

        inputStream.close();
        outputStream.close();

        System.err.println("upload e ...");
    }

}

浏览器访问:http://localhost:8080/app/uploadFile

点击上传

评论
条评论

推荐阅读