美文网首页
java文件上传demo

java文件上传demo

作者: 小小程序猿s | 来源:发表于2019-02-13 10:03 被阅读0次

import com.zqf.common.exception.ToUserException;
import com.zqf.common.utils.ServletUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**

  • @auth
    **/
    @Controller
    @RequestMapping("/upload")
    public class FileController {
    @RequestMapping(value = "/load",method = RequestMethod.POST)
    public void upload(HttpServletRequest req,HttpServletResponse res,@RequestParam("file") MultipartFile file){
    if(file.isEmpty()){
    throw new ToUserException("上传文件为空!");
    }
    Long time = System.currentTimeMillis();
    try {
    String orginateFileName = new String(file.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8");
    System.out.println("导入原始文件名:"+orginateFileName);
    System.out.println("导入原始文件大小:"+file.getSize());
    String fileName = time+"_"+orginateFileName;
    File localFile = new File("D://"+fileName);
    file.transferTo(localFile);
    ServletUtils.toJson(fileName,req,res);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    @GetMapping("/downLoad")
    public void download(String id, HttpServletRequest request, HttpServletResponse response) {
    System.out.println(id);
    try (
    FileInputStream inputStream = new FileInputStream(new File("D://"+id));
    ServletOutputStream outputStream = response.getOutputStream();
    ) {
    // 声明响应类型
    response.setContentType("application/x-download");
    // 下载的文件名称
    response.addHeader("Content-Disposition", "attachment;filename="+id);
    IOUtils.copy(inputStream, outputStream);
    //ServletUtils.toJson(request,response);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    }

相关文章

网友评论

      本文标题:java文件上传demo

      本文链接:https://www.haomeiwen.com/subject/dgjreqtx.html