SpringBoot 文件上传及下载

/**
 * SpringBoot方式启动类
 *
 */
@SpringBootApplication(scanBasePackages={"com.test"})
public class Application {
    protected final static Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
        logger.info("Application is sussess!");
    }
   
    // 设置 ajax 跨域
    @Bean
    public WebMvcConfigurer coresConfigurer(){
  return  new WebMvcConfigurerAdapter() {
   @SuppressWarnings("unused")
   public void addCorsMapping(CorsRegistry registry){
    registry.addMapping("/**").allowedOrigins("*");
   }
  };
    }
    @Bean
    public MultipartConfigElement multipartConfigElement(){
     MultipartConfigFactory factory = new  MultipartConfigFactory();
     factory.setMaxFileSize("20MB");
     factory.setMaxRequestSize("20MB");
     return factory.createMultipartConfig();
    }
   
}
-----------------------------------------------------------------------------------
### 上传文件路径
uploadurl:
    #linux
    duty.uploadurl: /usr/local/dutymtfile
    #window
    #duty.uploadurl: D:/dutymtfile 
-----------------------------------------------------------------------------------
@Controller
@RequestMapping("/honor")
public class ItmsDutyHonorController  extends BaseController{
 
 // 在配置文件,自动配置
 @Value("${uploadurl.duty.uploadurl}")
 private String uploadurl;
 
  @RequestMapping(value="/addUpdateHonor",method=RequestMethod.POST)
    @ResponseBody
 public JsonResult addUpdateCriticism(@RequestParam(value="file",required=false) MultipartFile multipartFile , HttpServletRequest request){ //@ModelAttribute("ItmsDutyHonor") ItmsDutyHonor honor,
        
      JsonResult jsonResult = new JsonResult();
        
         // System.out.println("==="+multipartFile.getOriginalFilename());
         // JSONObject jsonstr = new JSONObject();
         String strData = request.getParameter("data");
         ItmsDutyHonor honor =JSON.parseObject(strData, ItmsDutyHonor.class);
         
       
         int i = 0;
         try
         {
          if(null!=multipartFile && !multipartFile.isEmpty()){
           Calendar date = Calendar.getInstance();
           File file = new File(File.separator+date.get(Calendar.YEAR)+File.separator+(date.get(Calendar.MONTH)+1));
           System.out.println(file);
           if(!file.exists()){
            file.mkdirs();
           }
              //上传文件路径
           //String path = request.getSession().getServletContext().getRealPath("/mtfile/"+file);
           //System.err.println(uploadurl);
           String path = uploadurl+file;
           //获取
           String filename = multipartFile.getOriginalFilename();
           System.out.println(multipartFile.getSize());
           
           //自定义名字
           Date nowtime = new Date();
           String truefilename = String.valueOf(TimeUtil.getTimeStr(nowtime, TimeUtil.PATTERN_DATE_3))+"_"+filename;
           File filepath = new File(path,truefilename);
           if(!filepath.getParentFile().exists()){
            filepath.getParentFile().mkdirs();
           }
           multipartFile.transferTo(new File(path+File.separator+truefilename));
           honor.setMtfj("dutymtfile"+file+File.separator+truefilename);
           i = honorService.addUpdateHonor(honor);
             }else if(honor.getId()!=null){
              i = honorService.addUpdateHonor(honor);
             }
          
          if (i > 0)
          {
           jsonResult.setCode("200");
                 jsonResult.setMessage("success");
          }
          else
          {
           jsonResult.setCode("500");
                 jsonResult.setMessage("fail");
          }
         }
         catch(Exception ex)
         {
          ex.printStackTrace();
          jsonResult.setCode("500");
             jsonResult.setMessage("fail");
         }
         return  jsonResult;
     }
}
----------------------------------------------------------------------------------- 
 
 
 /**
  *
  *  @Description    : 下载附件;
  *  @Method_Name    : downfile;
  *  @param request
  *  @throws Exception
  *  @return         : void;
  *  @Creation Date  : 2018年3月2日 下午4:57:56 ;
  *  @version        : v1.00;
  *  @Author         : tao;
  *  @Update Date    :
  *  @Update Author  : who;
  */
 @RequestMapping("/downfile")
 public void downfile(HttpServletRequest request) throws Exception{
  //现将保存的参数  保存成文本形式  然后再下载到本地
  String fname = URLDecoder.decode(request.getParameter("fileUrl"), "UTF-8");
  //String docPath = request.getRealPath("") + File.separator + "dutymtfile" + File.separator + fname;
  
  String docPath =  uploadurl +File.separator + fname;
  
  System.out.println("docPath:" + docPath);
  FileInputStream in = null;
  OutputStream outp = null;
  try {
   // 设置响应头和保存文件名
   // response.reset();
   response.setCharacterEncoding("UTF-8");
   response.setContentType("application/x-download");
   response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fname, "UTF-8") + "\"");
   outp = response.getOutputStream();
   in = new FileInputStream(new File(docPath));
   byte[] b = new byte[1024];
   int i = 0;
   while((i = in.read(b)) > 0){
    outp.write(b, 0, i);
   }
   outp.flush();
   //out.clear();
   //out = pageContext.pushBody();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if(in != null){
    in.close();
   }
   if(outp != null){
    outp.close();
   }
  }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ITdada

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值