SpringBoot筆記8:簡單文件上傳與下載

控制器FileApiControllerjava

 

 

文件下載

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by WangXH
 * Date 2017-8-25.
 * desc:文件api
 */
@RestController
@RequestMapping("api/file")
public class FileApiController extends BaseApiController {


    /**
     * 下載文件示例
     * @param response
     * @throws IOException
     */
    @GetMapping("download")
    public void downloadFile(HttpServletResponse response)
            throws IOException {
        String filePath = Contants.TEMP_UPLOAD_DIR+"text.txt";
        File file = FileKit.mkDirs(filePath);
        if (file.exists()){
            download(file,response);
        }
    }
 
}

 

Contants.TEMP_UPLOAD_DIR 是文件存放的目錄web

/**
     * 臨時目錄
     * 
     */
    public static final String TEMP_UPLOAD_DIR=System.getProperty("user.dir")+"/temp/";

具體download方法實現:spring

protected void  download(File file, HttpServletResponse response){
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());

        InputStream in = null;
        OutputStream out = null;

        try {
            in = new FileInputStream(file.getPath());
            int len = 0;
            byte[] buffer = new byte[1024];
            out = response.getOutputStream();
            while((len = in.read(buffer)) > 0) {
                out.write(buffer,0,len);
            }

        }catch(Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(in != null) {
                try {
                    in.close();
                }catch(Exception e) {
                    throw new RuntimeException(e);
                }

            }
        }
    }

 

文件上傳

@PostMapping("upload")
    public ResultData uploadFile(MultipartHttpServletRequest multiReq){
        ResultData resultData=ResultData.makeFailResult("文件上傳失敗");
        MultipartFile multipartFile = multiReq.getFile("file");
        //獲取文件後綴   doc  jpg txt  等
        String postfix = FileKit.getPostfix(multipartFile.getOriginalFilename());

        File saveFile=new File(Contants.TEMP_UPLOAD_DIR+System.currentTimeMillis()+"."+postfix);
        try {
            FileOutputStream fos=new FileOutputStream(saveFile);
            byte[] buffer=new byte[1024];
            int len=0;
            FileInputStream fis= (FileInputStream) multipartFile.getInputStream();
            while((len=fis.read(buffer))!=-1){
                fos.write(buffer, 0, len);
            }
            fos.close();
            fis.close();
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("path",saveFile.getPath());
            resultData=ResultData.makeSuccessResult(jsonObject);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return resultData;
    }

配置文件 application.ymljson

spring:
  http:
    multipart:
      max-file-size: "100MB" # 最大文件上傳限制
相關文章
相關標籤/搜索