Upload file version
public void upload2(HttpServletRequest request , HttpServletResponse response){ //Create a generic multipart parser CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); //Determine whether the request has a file upload, that is, a multipart request (that is, check whether there is enctype="multipart/form-data" in the form) if(multipartResolver.isMultipart(request)){ //Convert to multipart request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //Get the name of all inputs in the request Iterator<String> iter = multiRequest.getFileNames(); while(iter.hasNext()){ //Get all uploaded files in an input List<MultipartFile> list = multiRequest.getFiles(iter.next()); for(MultipartFile file : list){ if(file != null){ //Get the file name of the currently uploaded file String myFileName = file.getOriginalFilename(); //If the name is not "", the file exists, otherwise the file does not exist if(myFileName.trim() != null){ //Rename the uploaded file name String saveName = UUID.randomUUID().toString() + myFileName.substring(myFileName.lastIndexOf(".")); //Define the upload path File localFile = new File("C:\\test\\",saveName); try { //keep file.transferTo(localFile); } catch (IllegalStateException e) { e.printStackTrace (); } catch (IOException e) { e.printStackTrace (); } } } } } } }
File Download Universal
// file path String filePath = basePath + fileName; try { File file = new File(filePath); if (file.exists()) { InputStream fis = new BufferedInputStream(new FileInputStream( filePath)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); // clear the response response.reset(); // Set the Header of the response response.addHeader("Content-Disposition","attachment;filename=" + new String(fileName.getBytes("iso8859-1"),"UTF-8")); response.addHeader("Content-Length", "" + file.length()); OutputStream toClient = new BufferedOutputStream( response.getOutputStream()); response.setContentType("application/octet-stream"); toClient.write(buffer); toClient.flush(); toClient.close(); } else { String errorMsg = "No file found, path: " + filePath; } } catch (Exception e) { String errorMsg = "File download, an exception occurred: " + e.getMessage(); }