1. 程式人生 > >Springboot上傳檔案

Springboot上傳檔案

Controler層裡面程式碼內容

@RequestMapping(value="/uploadImg", method=RequestMethod.POST)
@ResponseBody
public String uploadImgController(@RequestParam(value="img")MultipartFile img){
    File f = new File("/images");
    try{
        FileUtils.copyInputStreamToFile(img.getInputStream(), f);
    }catch(Exception e){
        e.printStackTrace();
    }
    return "上傳成功";
}

new File裡面的路徑是檔案儲存路徑
HTML檔案內容

 <form action="http://localhost/component/common/uploadImg" method="post" enctype="multipart/form-data">
     頭像:<input type="file" name="img" /><br/>
     <input type="image" src="./images/img_submit.gif" />
 </form>

以上是直接上傳檔案到指定目錄下,如果需要得到儲存圖片的路徑,修改如下:
controller層

@RequestMapping(value="/uploadImg", method=RequestMethod.POST)
@ResponseBody
public String uploadImgController(@RequestParam(value="img")MultipartFile img, HttpServletResponse response){
    JSONObject result = new JSONObject();
    boolean flag = true;
    try {
        flag = pictureUploadService.upload(img, result);
    } catch (Exception e) {
        result.put("mess", "呼叫失敗");
        flag = false;
        e.printStackTrace();
    }
    result.put("flag", flag);

    response.setContentType("text/html;charset=UTF-8");
    //解決跨域名訪問問題
    response.setHeader("Access-Control-Allow-Origin", "*");

    return result.toString();
}

service層

/**
 * 上傳圖片
 * @param file
 * @param params
 * @return
 * @throws Exception
 */
public boolean upload(MultipartFile file, JSONObject params) throws Exception{
    //過濾合法的檔案型別
    String fileName = file.getOriginalFilename();
    String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
    String allowSuffixs = "gif,jpg,jpeg,bmp,png,ico";
    if(allowSuffixs.indexOf(suffix) == -1){
        params.put("resultStr", "not support the file type!");
        return false;
    }
//生成唯一的檔名
    public  String getUniqueFileName() {
        String str = UUID.randomUUID().toString();
        return str.replace("-", "");
    }

    //獲取網路地址、本地地址頭部
    Properties config = new Properties();
    config.load(this.getClass().getClassLoader().getResourceAsStream("config.properties"));
    String urlPath = config.getProperty("urlRoot");
    String localPath = config.getProperty("localRoot");

    //建立新目錄
    String uri = File.separator + DateUtil.getNowDateStr(File.separator);
    File dir = new File(localPath + uri);
    if(!dir.exists()){
        dir.mkdirs();
    }

    //建立新檔案
    String newFileName = StringUtil.getUniqueFileName();
    File f = new File(dir.getPath() + File.separator + newFileName + "." + suffix);

    //將輸入流中的資料複製到新檔案
    FileUtils.copyInputStreamToFile(file.getInputStream(), f);

    String Url = (urlPath + uri.replace("\\", "/")  + newFileName + "." + suffix);
    //插入到資料庫
    //...

    params.put("resultStr", Url);

    return true;
}

以上就是上傳檔案的寫法,我也是看的別人的。