Java file upload and download

File entity class

/**
 * Document entity
 * @author luochen
 */
@Entity
@Table(name = "awards_attachment")
public class AwardsAttachment {
    @Id
    @GeneratedValue
    private Long attachmentId;
    /**
     * file type
     */
    private String attachmentType;
    /**
     * File name
     */
    private String fileName;
    /**
     * File path
     */
    private String filePath;
    /**
     * Creation time
     */
    private Date createTime;
    /**
     * Modification time
     */
    private Date updateTime;
    /**
     * Delete identity [1: delete, 0 normal]
     */
    private String delflag;

    public String getDelflag() {
        return delflag;
    }

    public void setDelflag(String delflag) {
        this.delflag = delflag;
    }

    public Long getAttachmentId() {
        return attachmentId;
    }

    public void setAttachmentId(Long attachmentId) {
        this.attachmentId = attachmentId;
    }

    public String getAttachmentType() {
        return attachmentType;
    }

    public void setAttachmentType(String attachmentType) {
        this.attachmentType = attachmentType;
    }

    public String getFileName() {
        return fileName;
    }

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

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}

 

The service class and implementation class of the file will not be written, that is, some methods of adding, deleting, modifying and querying.

 

File upload control class

/**
 * Resource downloading
 */
@RestController
@RequestMapping("data")
public class DataDownloadController {


    @Autowired
    private AwardsAttachmentService awardsAttachmentService;



    private static final Logger logger = LoggerFactory.getLogger(DataDownloadController.class);

    /**
     * Upload files
     *
     * @param upfile
     * @param type    file type
     * @param request
     */

    @PostMapping("/upload")
    @ApiOperation(value = "Upload files", notes = "Upload files", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "upfile", value = "file", required = true, dataType = "MultipartFile", paramType = "upfile")
    public JsonResponseExt uploadFile(@RequestParam(value = "file" ) MultipartFile upfile, @RequestParam(value = "type", required = false) String type, HttpServletRequest request) {


        //Date path
        String baseUrl = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";

        //String host = request.getHeader("Origin").substring(0, request.getHeader("Origin").lastIndexOf(":")) + ":" + request.getLocalPort();
        String host = request.getScheme()+"://"+request.getServerName() +":"+request.getLocalPort();
        String prePath = "";
        //Return result set
        Map<String, String> map = new HashMap<>();

        //Path prefix
        prePath = PropertyDbUtil.getPropertiesKey("DataDownload");
        //File name
        String fileName = upfile.getOriginalFilename();

        //File path
        String path = prePath + baseUrl;

        //File name after the virtual directory is saved
        //Files stored in virtual directory
        File uploadedFile = new File(path, fileName);
        
        File dest = uploadedFile.getParentFile();
        //Create if no directory exists
        if (!dest.exists()) {
            dest.mkdirs();
        }
        
        //File size limit
        long size = uploadedFile.length() / 1024 / 1024;
        if (size >= 10) {
            return JsonResponseExt.customFail("0032","The size of the uploaded file cannot be greater than 10 Mb");
        }
        try {
            //upload
            upfile.transferTo(uploadedFile);
            
            //Save attachments
            AwardsAttachment attachment = new AwardsAttachment();
            attachment.setFilePath(uploadedFile.getPath());
            if (!"".equals(type)) {
                attachment.setAttachmentType(type);
            }
            attachment.setFileName(fileName);
            attachment.setCreateTime(new Date());
            attachment.setDelflag("0");
            Long id = awardsAttachmentService.addAttachment(attachment).getAttachmentId();
            //Define return information
            String origin = host + "/data/down/" + id;
            map.put("id", id + "");
            map.put("name", fileName);
            map.put("filePath", uploadedFile.getPath());
            map.put("url", origin);

            return JsonResponseExt.success(map);

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return JsonResponseExt.customFail("0909","Upload failed!");
    }




    @GetMapping(value = "/down/{id}")
    public Object demo(@PathVariable("id") String id, String path, HttpServletRequest request, HttpServletResponse response) {

        if (!"".equals(id)) {
            AwardsAttachment tbAttachment = new AwardsAttachment();
            tbAttachment.setAttachmentId(Long.parseLong(id));
            AwardsAttachment awardsAttachment = awardsAttachmentService.findByAttachment(tbAttachment);

            try {
                // Download local file
                String fileName = awardsAttachment.getFileName();
                // Read in the stream
                InputStream inStream = new FileInputStream(awardsAttachment.getFilePath());
                // Format output
                response.reset();
                //Step 1: set the response type
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
                // Loop out the data in the stream
                byte[] b = new byte[100];
                int len;

                while ((len = inStream.read(b)) > 0) {
                    response.getOutputStream().write(b, 0, len);
                }
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JsonResponseExt.customFail("0033","error");
    }

 

    /**
     * file information
     * @param attachmentInfo
     * @param response
     * @return
     */
    @GetMapping(value = "/downFile")
    public JsonResponseExt fileDownload(AwardsAttachment attachmentInfo, HttpServletResponse response,HttpServletRequest request) {
        Map<String, String> map = new HashMap<String,String>();
        String host = request.getScheme()+"://"+request.getServerName() +":"+request.getLocalPort();
        AwardsAttachment info = awardsAttachmentService.findByAttachment(attachmentInfo);
        String origin =host+"/data/down/" + info.getAttachmentId();
        String fileName = info.getFileName();

        map.put("url",origin);
        map.put("name",fileName);
        map.put("path",info.getFilePath());
        return JsonResponseExt.success(map);
    }








}

 

 

 

page

<span class="info-item-status approval" @click="downFile(associatedMsg.creditCodeSample)"><i class="el-icon-tickets"></i></span>
//File download
    downFile(url){

      var elemIF = document.createElement("iframe");
      elemIF.src = url;
      elemIF.style.display = "none";
      document.body.appendChild(elemIF);

    },
associatedMsg.creditCodeSample is the file path, similar to the following path (path plus file id). Why use this path? In fact, my project is that the front-end and the back-end are separated, so the port numbers of the front-end and the back-end are inconsistent. At the same time, if they are
Directly access the download interface according to the file id. I find that the file stream is returned, and the download box will not pop up automatically for download. If it is in the form of a file stream, it needs to be Blob type, and the file name cannot be determined. If it needs to have a file name
It's like sending a request to get the file information. If you save the following form of link address, click it directly to request this interface to download.

File stream form

let url = window.URL.createObjectURL(new Blob([File stream]))
let a= document.createElement('a');
a.style.display = 'none';
a.href = url;
a.setAttribute('download', Document name and suffix);
document.body.appendChild(a)
a.click();


If your other entity class stores the file id, you can obtain the file information according to the file id and download it. [

this.$sysApi.fileMsg(), which is actually a get method

]

download(row) {
        this.$sysApi.fileMsg({"attachmentId":row.fileId}).then(res =>{
          console.log(res,"file");
          var elemIF = document.createElement("iframe");
          elemIF.src = res.data.url;
          elemIF.style.display = "none";
          document.body.appendChild(elemIF);
        });
}

Tags: Java

Posted on Sun, 01 Dec 2019 19:08:25 -0800 by allelopath