上传文件到物理路径并下载

上传文件到物理路径并下载

  1. 上传文件到服务器物理路径,以便下载使用

    接口如下:

    /**
     * 
    * @TODO:  小程序上传单个文件到服务器
    * @param request
    * @param file 文件
    * @throws IOException 
    * @return(展示方法参数和返回值)
     */
    @ResponseBody
    @RequestMapping("/fileUpload")
    public String fileUpload(@RequestParam("file") MultipartFile file){
        Map<String, Object> res = new HashMap<String, Object>();
    	String fileName = UUID.randomUUID().toString().replaceAll("-", "") + getSuffix(file);
    	// 判断是否有文件
    	if (StringUtils.isNotBlank(fileName)) {
            String uploaddir= "d:/upload/";
    		File upload = new File(uploaddir);
    		if(!upload.exists()) {
    			upload.mkdirs();
    		}
    		File fileinfo=new File(String.format("%s%s", uploaddir, fileName));
    		try {
    			FileUtils.writeByteArrayToFile(fileinfo, file.getBytes());
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		res.put("fileName", fileName);
    	}
    	res.put("success", "success");
    	String json = JSON.toJSONString(res);
    	return json;
    }
    

该接口实现的是文件上传到指定路径(“d:/upload/”)下,并返回生成的文件名用于下载

  1. 下载物理路径中的图片

    /**
    	 * 
    	* @TODO: 下载图片 
    	* @param fileId
    	* @return(展示方法参数和返回值)
    	*/
        @ResponseBody
    	@RequestMapping("/getImg")
        public BaseResponse getFile(@RequestParam("fileId")  String fileId) {
        	//文件上传到服务器之后,文件路径保存到数据库中,在这里获取路径以便下载使用
        	String imgUrl = testService.selectImgUrlById(fileId); 
        	String filePath = "d:/upload/" +  imgUrl;
        	
            String imgBase64 =  WechatDownload.downloadCheckEquipmentImg(filePath);
    		return BaseResponseUtil.success("data:image/png;base64," + imgBase64);
        }
    

猜你喜欢

转载自blog.csdn.net/ampsycho/article/details/86003200