運用springboot實現文件上傳和下載的功能

文件上傳和讀取是項目開發中必備的功能,前幾天開發項目的時候自己研究出來的,總結一下爲以後項目開發積累經驗,方法很簡單,配置文件存放路徑,然後加一個虛擬路徑映射使得用戶能從瀏覽器訪問文件。

文件處理類

package com.scs.util;

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

public class FileUtil {

	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + fileName);
		out.write(file);
		out.flush();
		out.close();
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		// 如果文件路徑所對應的文件存在,並且是一個文件,則直接刪除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public static String renameToUUID(String fileName) {
		return UUID.randomUUID() + "." + fileName.substring(fileName.lastIndexOf(".") + 1);
	}
}

配置文件讀取類:

/**
 * projectName:  skb.com
 * fileName:
 * packageName:
 * date: 2018年11月28日下午12:28:39
 * copyrightc 2017-2020 aoSoft公司
 * desc :
 */
package com.scs.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Set;

import org.apache.tomcat.util.http.fileupload.IOUtils;

/**
 * 配置文件讀取
 */
public class PropertiesUtil {

    private static Properties properties = null;
    
    public static String getProperty(String key)
    {
    	return null == properties ? "" : properties.getProperty(key);
    }

    /**
     * 加載主配置文件,並初始化相關信息
     */
    static{
        if(properties==null){
            loadProperties();
        }
    }

    private static void loadProperties(){
        List<String> fileNameList = new ArrayList<>();
        fileNameList.add("application.properties");

        Properties p = new Properties();
        InputStream in = null;
        try
        {
        	properties = new Properties();
            for (String fileName : fileNameList)
            {
                in = PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName);
                p.load(in);

                Set<Object> keySet = p.keySet();

                Iterator<Object> it = keySet.iterator();
                while (it.hasNext())
                {
                    Object key = it.next();
                    properties.put(key.toString(), p.getProperty(key.toString()));
                }
            }
        }
        catch (IOException e)
        {
            System.out.println(e.getMessage());
        }
        finally
        {
            if (null != in)
            {
                IOUtils.closeQuietly(in);
            }
        }
    }
 
    
}

Controller層方法

  @ResponseBody
   	@PostMapping("/upload")
       public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
       	ResultEntity resultEntity = new ResultEntity();
   		try {
   			String fileName = file.getOriginalFilename();
   			fileName = FileUtil.renameToUUID(fileName);
   			//FileUtil.uploadFile(file.getBytes(), PropertiesUtil.getProperty("upload.file.dir"), fileName);
   			 //文件臨時存儲位置
   			String type = "user";
   			if ("2".equals(request.getParameter("type"))) {//1營業執照/報關材料
   				type = "customsMaterials";
   				Resource bean = new Resource();
//   				bean.setMainId(request.getParameter("id"));
   				bean.setResourceName(file.getOriginalFilename());
   				bean.setResourceContent(type+"/"+fileName);
   				bean.setResourceType("1");
   				bean.setSkillPointId(1);
//   				bean.setUserId(request.getParameter("userId"));
//   				bean.setFileName(file.getOriginalFilename());
//   				bean.setUrl(type+"/"+fileName);
//   				bean.setType("2");
//   				attachmentService.add(bean);
   				teacherservice.insertResource(bean);
   				
//   				OrderInfoDO orderInfo = new OrderInfoDO();
//   				orderInfo.setOrderId(request.getParameter("id"));
//   				orderInfo.setVesselEntryFileFlag("1");
//   				orderInfoService.update(orderInfo);
   			}
   			Resource bean = new Resource();
			bean.setResourceName(file.getOriginalFilename());
			bean.setResourceContent(type+"/"+fileName);
			bean.setResourceType("1");
			bean.setSkillPointId(1);
			teacherservice.insertResource(bean);
               //String path = request.getSession().getServletContext().getRealPath("") + "files/upload/img/"+type+"/";
   			String path = PropertiesUtil.getProperty("upload.file.dir")+type+"/";
   			System.out.println(path);
   			FileUtil.uploadFile(file.getBytes(), path, fileName);
   			List<String> list = new ArrayList<String>();
   			list.add(type+"/"+fileName);
   			//list.add(fileName);
   			list.add(file.getOriginalFilename());
   			list.add(request.getScheme()+"://"+ request.getServerName()+":"+request.getServerPort()+request.getContextPath()  + PropertiesUtil.getProperty("upload.file.dir")+type+"/"+fileName);			
   			resultEntity.setResultList(list);
   			resultEntity.setResultMsg("上成功");
   		} catch (Exception e) {
   			e.printStackTrace();
   			resultEntity.setResultCode(Constants.ERROR_CODE);
               resultEntity.setResultMsg("上傳失敗:"+e.getMessage());
   		}
           return JSONObject.toJSONString(resultEntity);
   	}

application.properties配置

upload.file.dir =/root/reco/

注意Linux和Windows路徑不一樣,此處爲Linux系統路徑配置

配置虛擬路徑映射

package com.scs.util;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;



/**
 * 圖片絕對地址與虛擬地址映射
 */
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {
 
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //和頁面有關的靜態目錄都放在項目的static目錄下
        //registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        //上傳的圖片在D盤下的OTA目錄下,訪問路徑如:http://localhost:8081/OTA/d3cf0281-bb7f-40e0-ab77-406db95ccf2c.jpg
        //其中OTA表示訪問的前綴。"file:D:/OTA/"是文件真實的存儲路徑
        //registry.addResourceHandler("/static/upload/**").addResourceLocations("file:D:/upload/");
    	//registry.addResourceHandler("/static/upload/**").addResourceLocations("file:" + PropertiesUtil.getProperty("upload.file.dir"));
    	registry.addResourceHandler("/static/upload/**").addResourceLocations("file:" + PropertiesUtil.getProperty("upload.file.dir"));
    }
}

然後訪問想要http://47.101.164.136:11219/static/upload/user/a3501f61-4f44-4291-988c-ddbe47701bb7.pdf即可得到文件路徑

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章