java file upload and download code example
- 2021-07-09 08:16:09
- OfStack
In this article, we share the specific code of uploading and downloading java files for your reference. The specific contents are as follows
File upload
@RequestMapping(value="/uploadFile",method=RequestMethod.POST)
public ResultObject uploadFiles(@RequestParam("file")MultipartFile file,HttpServletRequest request){
ResultObject rs = null;// Return upload completion information
String uploadDir = "files";// Upload directory , Files are saved in webapp Under files In a file
if(!file.isEmpty()) {
// Can be right user Do 1 Some operations such as storing in the database
// The following code is to set the file file Rename and save to Tomcat Adj. webapp Subdirectory of the project under the directory
String fileRealName = file.getOriginalFilename(); // Get the original file name ;
/*int pointIndex = fileRealName.indexOf("."); // Position of the dot
String fileSuffix = fileRealName.substring(pointIndex); // Intercept file suffix
UUID FileId = UUID.randomUUID(); // The prefix of the generated file contains a hyphen
String savedFileName = FileId.toString().replace("-", "").concat(fileSuffix); // File access name
*/
String savedDir = request.getSession().getServletContext().getRealPath(uploadDir); // Gets the file access path specified by the server
File savedFile = new File(savedDir, fileRealName);
boolean isCreateSuccess;
try {
isCreateSuccess = savedFile.createNewFile();
if (isCreateSuccess) {
file.transferTo(savedFile); // Transfer document
rs = ResultObject.getSuccessResult(" Upload File Successfully ");
Long size = file.getSize();// Get the file size
rs.setData(uploadDir+fileRealName);
}else{
rs = ResultObject.getFailResult(" Please modify the file name , Re-upload ");
}
} catch (IOException e) {
e.printStackTrace();
}
}else{
rs = ResultObject.getFailResult(" File cannot be empty ");
}
return rs;
}
File download
@RequestMapping(value = "/filterPermission/appDownLoad", method = RequestMethod.GET)
public void appDownLoad(HttpServletRequest request, HttpServletResponse response) {
//url It was uploaded from the above file url
download(url,request,response);
}
public String download(String filePath, HttpServletRequest request, HttpServletResponse response) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
// Get the file name
String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
//response.setContentType("application/force-download");
// Dealing with the encoding of download pop-up box names
response.setHeader("Content-Disposition", "attachment;fileName="
+ new String( fileName.getBytes("gb2312"), "ISO8859-1" ));
// Get the download path of the file
String path = request.getSession().getServletContext().getRealPath(filePath);
// Download files using input and output streams
InputStream inputStream = new FileInputStream(new File(path));
// Set file size
response.setHeader("Content-Length", String.valueOf(inputStream.available()));
bis = new BufferedInputStream(inputStream);// Construct a read stream
bos = new BufferedOutputStream(response.getOutputStream());// Construct output stream
byte[] buff = new byte[1024];
int bytesRead;
// Every time you read the cache size stream, write to the output stream
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
response.flushBuffer();// Return all read streams to the client
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
if(null != bis){
bis.close();
}
if(null != bos){
bos.close();
}
}catch(IOException e){
System.out.println(" Failed to download file ,"+" File path :"+filePath+e);
logger.error(" File download failed !", e);
}
}
// Pay attention to the return value, or the following error will appear!
//java+getOutputStream() has already been called for this response
return null;
}