如何實現文件上傳 - 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();
    }
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM