Loading

如何实现文件上传 - JavaWeb

直接上代码 ( idea 开发,SpringBoot 框架 ):

首先是Controller的写法:

package com.xxx.Controller;

import com.xxx.Tools.ImgTool;
import com.xxx.bean.Msg;
import org.apache.tomcat.util.http.fileupload.FileUploadBase;
import org.apache.tomcat.util.http.fileupload.FileUploadBase.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/img")
public class ImgUploadController {

    @PostMapping(value = "/upload")
    public Msg uploadImg(@RequestParam(value = "img") MultipartFile img, HttpServletRequest request) throws IOException, FileSizeLimitExceededException {
        if (img == null){
            return Msg.fail().add("describe", "参数不能为空");
        } else {
            try {
                Map<String , Object> map = new HashMap<>();
                map = ImgTool.upload(img, request);
                if (map.get("resultStr").equals("300")){
                    return Msg.fail().add("describe", "文件格式不支持");
                } else {
                    return Msg.success().add("imgurl", map.get("resultStr"));
                }
            } catch (Exception e){
                return Msg.fail().add("describe", e);
            }
        }
    }
}

upload()函数所在的类,包含一些其他的tool方法 :

package com.xxx.Tools;

import com.xxx.bean.Picture;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class ImgTool {

    /**
     * 上传图片,并返回图片路径
     */
    public static Map<String, Object> upload(MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> map = new HashMap<>();

        //过滤合法的文件类型
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String allowSuffixs = "gif,jpg,jpeg,bmp,png,ico";
        if (allowSuffixs.indexOf(suffix) == -1){
            //300代表文件格式不支持
            map.put("resultStr", "300");
            System.out.println("文件格式不支持");
            return map;
        }

        //获取真实路径
        String localPath = request.getServletContext().getRealPath("/");

        //创建新目录
        String uri = File.separator + getNowDateStr(File.separator);
        File dir = new File(localPath + "/static/ProjectImgs/" + uri);
        if (!dir.exists()){
            dir.mkdirs();
        }

        //创建新文件
        String newFileName = getUniqueFileName();
        File f = new File(dir.getPath() + File.separator + newFileName + "." + suffix);

        //将输入流中的数据复制到新文件
        org.apache.commons.io.FileUtils.copyInputStreamToFile(file.getInputStream(), f);

        //创建picture对象
        Picture pic = new Picture();
        pic.setLocalPath(f.getAbsolutePath());
        pic.setName(f.getName());
        //将路径中的\\替换成/,符合浏览器的分级规则
        pic.setUrl(localPath.replace("\\", "/")
                + "static/ProjectImgs"
                + uri.replace("\\", "/") + "/" + newFileName + "." + suffix);

        //插入到数据库
        //...

        map.put("resultStr", pic.getUrl());

        return map;
    }

    /**
     * 获取当前日期字符串
     * @param separator
     * @return
     */
    public static String getNowDateStr(String separator){
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        //month 记得加一(因为默认从0开始计数)
        int month = now.get(Calendar.MONTH)+1;
        int day = now.get(Calendar.DATE);

        return year + separator + month + separator + day;
    }

    //生成唯一的文件名
    public static String getUniqueFileName(){
        String str = UUID.randomUUID().toString();
        return str.replace("-", "");
    }
}

Picture类:

package com.xxx.bean;

import java.util.Date;

public class Picture {

    private String localPath;
    private String name;
    private String url;
    private Date addTime;

    public Picture() {
    }

    public Picture(String localPath, String name, String url, Date addTime) {
        this.localPath = localPath;
        this.name = name;
        this.url = url;
        this.addTime = addTime;
    }

    public String getLocalPath() {
        return localPath;
    }

    public void setLocalPath(String localPath) {
        this.localPath = localPath;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public Date getAddTime() {
        return addTime;
    }

    public void setAddTime(Date addTime) {
        this.addTime = addTime;
    }
}

在通常的Web开发中,上面的通用写法只要稍加改动边可以适应自己的项目需求,比如在SSM框架中需要在dispatchServlet.xml中设置上传文件的各种限制;

SpringBoot中可以在.yml文件中配置文件路径,在项目起始的Application类中配置文件大小属性。

下面是SpringBoot中配置文件大小的参考写法,写在类ShouguoApplication,即入口程序段中:

package com.xxx;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import javax.servlet.MultipartConfigElement;

@SpringBootApplication
public class ShouguoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShouguoApplication.class, args);
    }

    /**
     * 文件上传配置
     */
    @Bean
    public MultipartConfigElement multipartConfigElement(){
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //maxSize
        factory.setMaxFileSize("10240KB");
        //设置总上传数据总大小
        factory.setMaxRequestSize("102400KB");
        return factory.createMultipartConfig();
    }
}

 

 

posted @ 2018-05-02 20:26  sinatJ  阅读(1847)  评论(0编辑  收藏  举报