springboot 項目實現文件上傳,顯示,下載,打包為jar


文件上傳是Web中常見的功能,選擇性也很多,比如將文件上傳到oss等類似的文件服務器上,這種方式成本比較高。文件的上傳和顯示操作比較簡單。另外就是在文件上傳到項目路徑的靜態資源文件夾resources/下。還可以上傳到mongodb中。

這次使用Springboot提供了的靜態資源的映射方式

你可以添加一個外部文件夾並將其作為一個靜態資源文件夾的映射,也就是說添加這個映射后你可以在項目中像訪問靜態資源文件夾一樣來訪問外部的文件夾。

具體代碼:

在項目中新建一個類,創建映射的靜態資源請求路徑。

package com.herbert.upload.controller;
 
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 
/**
 * Created by Herbert on 2020/4/8.
 * zhaixingzu@163.com
 */
 
@Configuration
public class WebAppConfig implements WebMvcConfigurer {
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
        registry.addResourceHandler("/img/**").addResourceLocations("file:F:/img/");
    }
}
"/img/**" 就是映射的靜態資源請求路徑

下來測試下靜態資源是否配置成功:

在F盤符下建立文件夾img 。然后放一張圖片為code.png 通過映射的靜態資源請求路徑訪問:

啟動項目

 

 

 

 訪問http://127.0.0.1:8080/img/code.png

 

 

 上傳文件代碼:

package com.herbert.upload.controller;
 
import com.alibaba.fastjson.JSON;
import com.wwj.imageupload.util.FileUtils;
import org.springframework.ui.Model;
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.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;
 
@RestController
public class ImageUploadController {
 
   
    @RequestMapping("/imageUpload")
    public Map imageUpload(@RequestParam("fileName") MultipartFile file){
        String result_msg="";//上傳結果信息
 
        Map<String,Object> root=new HashMap<String, Object>();
        if (file.getSize() / 1000 > 100){
            result_msg="圖片大小不能超過100KB";
        }else{
            //判斷上傳文件格式
            String fileType = file.getContentType();
            if (fileType.equals("image/jpeg") || fileType.equals("image/png") || fileType.equals("image/jpeg")) {
                // 要上傳的目標文件存放的絕對路徑
                //用src為保存絕對路徑不能改名只能用原名,不用原名會導致ajax上傳圖片后在前端顯示時出現404錯誤-->原因未知
//                String localPath="F:\\IDEAProject\\imageupload\\src\\main\\resources\\static\\img";
                final String localPath="F:\\img";
                //上傳后保存的文件名(需要防止圖片重名導致的文件覆蓋)
                //獲取文件名
                String fileName = file.getOriginalFilename();
                //獲取文件后綴名
                String suffixName = fileName.substring(fileName.lastIndexOf("."));
                //重新生成文件名
                fileName = UUID.randomUUID()+suffixName;
                if (FileUtils.upload(file, localPath, fileName)) {
                    //文件存放的相對路徑(一般存放在數據庫用於img標簽的src)
                    String relativePath="img/"+fileName;
                    root.put("relativePath",relativePath);//前端根據是否存在該字段來判斷上傳是否成功
                    result_msg="圖片上傳成功";
                }
                else{
                    result_msg="圖片上傳失敗";
                }
            }
            else{
                result_msg="圖片格式不正確";
            }
        }
        root.put("result_msg",result_msg);
        String root_json=JSON.toJSONString(root);
        System.out.println(root_json);
        return root;
    }
 
   
}

下載代碼:

 @RequestMapping("/download")
    public void downLoad(HttpServletResponse response) throws UnsupportedEncodingException {
        String filename="code.png";
        String filePath = "F:\\img" ;
        File file = new File(filePath + "/" + filename);
        if(file.exists()){
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename,"utf8"));
            byte[] buffer = new byte[1024];
            //輸出流
            OutputStream os = null;
            try(FileInputStream fis= new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);) {
                os = response.getOutputStream();
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

測試上傳,下載功能:

 

 

 

 

 

 

到此:圖片上傳,顯示功能已經完成。

下來測試下載功能

 

 

 

源碼下載:https://download.csdn.net/download/weixin_41986096/12315498

 

 


免責聲明!

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



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