java implements the method of saving files locally

  • 2020-06-01 09:52:55
  • OfStack

This article introduces the method to save the java implementation file locally. The specific code is as follows:


private void savePic(InputStream inputStream, String fileName) {

    OutputStream os = null;
    try {
      String path = "D:\\testFile\\";
      // 2 Save to a temporary file 
      // 1K Data buffering 
      byte[] bs = new byte[1024];
      //  Length of data read 
      int len;
      //  The output file stream is saved to a local file 

      File tempFile = new File(path);
      if (!tempFile.exists()) {
        tempFile.mkdirs();
      }
      os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
      //  Began to read 
      while ((len = inputStream.read(bs)) != -1) {
        os.write(bs, 0, len);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      //  Over, close all links 
      try {
        os.close();
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

File saving method.

The attached:


package com.ebways.web.upload.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import com.ebways.web.base.BaseController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ebways.web.upload.url.UploadURL;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping(value = UploadURL.MODE_NAME)
public class UploadController extends BaseController {

  @RequestMapping(value = UploadURL.IMAGE_UPLOAD)
  @ResponseBody
  public String uploadFile(MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IllegalArgumentException, Exception {
    //  The list of parameters 
    Map<String, Object> map = new HashMap<>();
    map.put("file", file);
    savePic(file.getInputStream(), file.getOriginalFilename());

    // Request interface 
    String apiReturnStr = "";//apiHttpRequest(map, API_HOST_URL + "/image/upload");

    return apiReturnStr;
  }

  private void savePic(InputStream inputStream, String fileName) {

    OutputStream os = null;
    try {
      String path = "D:\\testFile\\";
      // 2 Save to a temporary file 
      // 1K Data buffering 
      byte[] bs = new byte[1024];
      //  Length of data read 
      int len;
      //  The output file stream is saved to a local file 

      File tempFile = new File(path);
      if (!tempFile.exists()) {
        tempFile.mkdirs();
      }
      os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
      //  Began to read 
      while ((len = inputStream.read(bs)) != -1) {
        os.write(bs, 0, len);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      //  Over, close all links 
      try {
        os.close();
        inputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * <p class="detail">
   *  Function: public Action
   * </p>
   *
   * @date 2016 years 9 month 8 day 
   * @author wangsheng
   */
  private String allowSuffix = "jpg,png,gif,jpeg";// Allowed file format 
  private long allowSize = 2L;// Allowed file size 
  private String fileName;
  private String[] fileNames;

  public String getAllowSuffix() {
    return allowSuffix;
  }

  public void setAllowSuffix(String allowSuffix) {
    this.allowSuffix = allowSuffix;
  }

  public long getAllowSize() {
    return allowSize * 1024 * 1024;
  }

  public void setAllowSize(long allowSize) {
    this.allowSize = allowSize;
  }

  public String getFileName() {
    return fileName;
  }

  public void setFileName(String fileName) {
    this.fileName = fileName;
  }

  public String[] getFileNames() {
    return fileNames;
  }

  public void setFileNames(String[] fileNames) {
    this.fileNames = fileNames;
  }


  /**
   * <p class="detail">
   *  Function: rename file 
   * </p>
   *
   * @return
   * @author wangsheng
   * @date 2016 years 9 month 8 day 
   */
  private String getFileNameNew() {
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    return fmt.format(new Date());
  }

  /**
   * <p class="detail">
   *  Function: file upload 
   * </p>
   *
   * @param files
   * @param destDir
   * @throws Exception
   * @author wangsheng
   * @date 2014 years 9 month 25 day 
   */
  public void uploads(MultipartFile[] files, String destDir, HttpServletRequest request) throws Exception {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
    try {
      fileNames = new String[files.length];
      int index = 0;
      for (MultipartFile file : files) {
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        int length = getAllowSuffix().indexOf(suffix);
        if (length == -1) {
          throw new Exception(" Please upload the file in the allowed format ");
        }
        if (file.getSize() > getAllowSize()) {
          throw new Exception(" The file size you uploaded is out of range ");
        }
        String realPath = request.getSession().getServletContext().getRealPath("/");
        File destFile = new File(realPath + destDir);
        if (!destFile.exists()) {
          destFile.mkdirs();
        }
        String fileNameNew = getFileNameNew() + "." + suffix;//
        File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew);
        file.transferTo(f);
        f.createNewFile();
        fileNames[index++] = basePath + destDir + fileNameNew;
      }
    } catch (Exception e) {
      throw e;
    }
  }

  /**
   * Function: file upload 
   *
   * @param file
   * @param destDir
   * @throws Exception
   * @author wangsheng
   * @date 2016 years 9 month 8 day 
   */
  public void upload(MultipartFile file, String destDir, HttpServletRequest request) throws Exception {
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
    try {
      String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
      int length = getAllowSuffix().indexOf(suffix);
      if (length == -1) {
        throw new Exception(" Please upload the file in the allowed format ");
      }
      if (file.getSize() > getAllowSize()) {
        throw new Exception(" The file size you uploaded is out of range ");
      }

      String realPath = request.getSession().getServletContext().getRealPath("/");
      File destFile = new File(realPath + destDir);
      if (!destFile.exists()) {
        destFile.mkdirs();
      }
      String fileNameNew = getFileNameNew() + "." + suffix;
      File f = new File(destFile.getAbsoluteFile() + "/" + fileNameNew);
      file.transferTo(f);
      f.createNewFile();
      fileName = basePath + destDir + fileNameNew;
    } catch (Exception e) {
      throw e;
    }
  }

}


Related articles: