Java file multipart upload Server Source Code

Source: Internet
Author: User

Directly add the code. The source code of the Spring MVC Controller that receives client HTTP multipart upload requests is as follows: [java] @ Controller public class UploadController extends BaseController {private static final Log log = LogFactory. getLog (UploadController. class); private UploadService uploadService; private AuthService authService;/*** the large file is divided into small file blocks for upload. One part is transferred at a time. After the last part is uploaded successfully, merge all uploaded parts, save them to the corresponding location on File Server *, and return the detailed attributes of the successfully uploaded files. when the last part is uploaded, the information about the successful upload is returned. In this case, use getFileList to query the file. * The file's uploadStatus is 2. The client must handle the display of files in this status. (For UPS Server) **/@ RequestMapping ("/core/v1/file/upload") @ ResponseBody public Object upload (HttpServletResponse response, @ RequestParam (value = "client_id ", required = false) String appkey, @ RequestParam (value = "sig", required = false) String appsig, @ RequestParam (value = "token", required = false) String token, @ RequestParam (value = "uuid", required = false) String uuid, @ RequestParam (value = "Block", required = false) String blockIndex, @ RequestParam (value = "file", required = false) MultipartFile multipartFile, @ RequestParam Map <String, String> parameters) {checkEmpty (appkey, BaseException. ERROR_CODE_16002); checkEmpty (token, BaseException. ERROR_CODE_16007); checkEmpty (uuid, BaseException. ERROR_CODE_20016); checkEmpty (blockIndex, BaseException. ERROR_CODE_20006); checkEmpty (appsig, BaseException. ERROR_CODE_10010); if (multipartFile = null) {throw new BaseException (BaseException. ERROR_CODE_20020); // the uploaded file does not exist} Long uuidL = parseLong (uuid, BaseException. ERROR_CODE_20016); Integer blockIndexI = parseInt (blockIndex, BaseException. ERROR_CODE_20006); Map <String, Object> appMap = getAuthService (). validateSigature (parameters); AccessToken accessToken = CasUtil. checkAccessToken (tok En, appMap); Long uid = accessToken. getUid (); String bucketUrl = accessToken. getBucketUrl (); // copy files from the upload directory to the working directory String fileAbsulutePath = null; try {fileAbsulutePath = this. copyFile (multipartFile. getInputStream (), multipartFile. getOriginalFilename ();} catch (IOException ioe) {log. error (ioe. getMessage (), ioe); throw new BaseException (BaseException. ERROR_CODE_20020); // the uploaded File does not exist} File uploadedFile = New File (Global. UPLOAD_TEMP_DIR + fileAbsulutePath); checkEmptyFile (uploadedFile); // file non-empty verification Object rs = uploadService. upload (uuidL, blockIndexI, uid, uploadedFile, bucketUrl); setHttpStatusOk (response); return rs ;} // TODO check whether there is a problem here // verify private void checkEmptyFile (File file) {if (file = null | File. getAbsolutePath () = null) {throw new BaseException (BaseException. ERROR_CODE_200 20); // the uploaded file does not exist}/*** write the file to the local folder ** @ throws IOException * returns the generated file name */private String copyFile (InputStream inputStream, string fileName) {OutputStream outputStream = null; String tempFileName = null; int pointPosition = fileName. lastIndexOf (". "); if (pointPosition <0) {// myvedio tempFileName = UUID. randomUUID (). toString (); // 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26} else {// myvedio. flv tempFile Name = UUID. randomUUID () + fileName. substring (pointPosition); // 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26.flv} try {outputStream = new FileOutputStream (Global. UPLOAD_TEMP_DIR + tempFileName); int readBytes = 0; byte [] buffer = new byte [10000]; while (readBytes = inputStream. read (buffer, 0, 10000 ))! =-1) {outputStream. write (buffer, 0, readBytes);} return tempFileName;} catch (IOException ioe) {// log. error (ioe. getMessage (), ioe); throw new BaseException (BaseException. ERROR_CODE_20020); // the uploaded file does not exist} finally {if (outputStream! = Null) {try {outputStream. close () ;}catch (IOException e) {}} if (inputStream! = Null) {try {inputStream. close ();} catch (IOException e) {}}}/*** test whether the service is available ** @ param response * @ return * @ author zwq7978 */@ RequestMapping ("/core/v1/file/testServer ") @ ResponseBody public Object testServer (HttpServletResponse response) {setHttpStatusOk (response); return Global. SUCCESS_RESPONSE;} public UploadService getUploadService () {return uploadService;} public void setUpload Service (UploadService uploadService) {this. uploadService = uploadService;} public void setAuthService (AuthService authService) {this. authService = authService;} public AuthService getAuthService () {return authService ;}}for example, the file to be uploaded is test450k.mp4. The upload method uses MultipartFile to receive this object, in contrast to the name defined by the block upload server for the block file parameter in Java file multipart upload client source code. For each HTTP request, use the copyFile method to output the file stream to a temporary folder on the server. For example, the author is D:/defonds/syncPath/uploadTemp, A temporary file named 50127019-b63b-4a54-8f53-14efd1e58ada.mp4 is generated to save the uploaded file stream. Upload parts in sequence. After all the blocks are uploaded, transfer these temporary files to the specified directory on the server. For example, the author's directory is D:/defonds/syncPath/file, in this folder, the/1/temp_dir_5_1 directory is generated, and the temporary file of uploadTemp is transferred to this folder one by one, which is generated as 5. part0001 file. The source code of file transfer is as follows: [java]/*** move all blocks from the temporary file directory to the specified local directory or S2/S3 ** @ param preUpload */private void moveBlockFiles (BlockPreuploadFileInfo preUpload) {@ SuppressWarnings ("unchecked") String [] s3BlockUrl = new String [preUpload. getBlockNumber ()]; String [] localBlockUrl = new String [preUpload. getBlockNumber ()]; // The Local block file path to delete the List <BlockUploadInfo> blocks = (List <BlockUploadInfo>) getBaseDao (). queryForList ("upload. g EtBlockUploadFileByUuid ", preUpload. getUuid (); String tempDirName = SyncUtil. getTempDirName (preUpload. getUuid (), preUpload. getUid (); String parentPath = Global. UPLOAD_ABSOLUTE_PAHT _ + Global. PATH_SEPARATIVE_SIGN + String. valueOf (preUpload. getUid (); String dirPath = parentPath + Global. PATH_SEPARATIVE_SIGN + tempDirName; new File (dirPath ). mkdirs (); // create a folder for storing Block Files (local) int j = 0; for (BlockUploadInfo Info: blocks) {try {String strBlockIndex = createStrBlockIndex (info. getBlockIndex (); String suffixPath = preUpload. getUuid () + ". part "+ strBlockIndex; String tempFilePath = info. getTempFile (); File tempFile = new File (tempFilePath); File tmpFile = new File (dirPath + suffixPath); if (tmpFile. exists () {FileUtils. deleteQuietly (tmpFile);} FileUtils. moveFile (tempFile, tmpFile); localBlockUrl [j] = DirPath + suffixPath; j ++; info. setStatus (Global. MOVED_TO_NEWDIR); getBaseDao (). update ("upload. updateBlockUpload ", info); if (log. isInfoEnabled () log.info (preUpload. getUuid () + "" + info. getBuId () + "moveBlockFiles");} catch (IOException e) {log. error (e. getMessage (), e); throw new BaseException ("file not found") ;}} preUpload. setLocalBlockUrl (localBlockUrl); preUpload. setDirPath (dirPath ); PreUpload. setStatus (Global. MOVED_TO_NEWDIR); getBaseDao (). update ("upload. updatePreUploadInfo ", preUpload);} private String createStrBlockIndex (int blockIndex) {String strBlockIndex; if (blockIndex <10) {strBlockIndex =" 000 "+ blockIndex ;} else if (10 <= blockIndex & blockIndex <100) {strBlockIndex = "00" + blockIndex;} else if (100 <= blockIndex & blockIndex <1000) {strBlockIndex = "0 "+ BlockIndex;} else {strBlockIndex =" "+ blockIndex;} return strBlockIndex;} The final source code for file assembly: [java]/*** Assembly file **/private void assembleFileWithBlock (BlockPreuploadFileInfo preUpload) {String dirPath = preUpload. getDirPath (); // start to assemble the file String uploadedUrl = null in the specified directory; String [] separatedFiles; String [] [] separatedFilesAndSize; int fileNum = 0; file file = new File (dirPath); separatedFiles = fil E. list (); separatedFilesAndSize = new String [separatedFiles. length] [2]; Arrays. sort (separatedFiles); fileNum = separatedFiles. length; for (int I = 0; I <fileNum; I ++) {separatedFilesAndSize [I] [0] = separatedFiles [I]; string fileName = dirPath + separatedFiles [I]; File tmpFile = new File (fileName); long fileSize = tmpFile. length (); separatedFilesAndSize [I] [1] = String. valueOf (fileSize);} RandomA CcessFile fileReader = null; RandomAccessFile fileWrite = null; long alreadyWrite = 0; int len = 0; byte [] buf = new byte [1024]; try {uploadedUrl = Global. UPLOAD_ABSOLUTE_PAHT _ + Global. PATH_SEPARATIVE_SIGN + preUpload. getUid () + Global. PATH_SEPARATIVE_SIGN + preUpload. getUuid (); fileWrite = new RandomAccessFile (uploadedUrl, "rw"); for (int I = 0; I <fileNum; I ++) {fileWrite. seek (alreadyWrite ); // Read fileReader = new RandomAccessFile (dirPath + separatedFilesAndSize [I] [0]), "r"); // write while (len = fileReader. read (buf ))! =-1) {fileWrite. write (buf, 0, len);} fileReader. close (); alreadyWrite + = Long. parseLong (separatedFilesAndSize [I] [1]);} fileWrite. close (); preUpload. setStatus (Global. ASSEMBLED); preUpload. setServerPath (uploadedUrl); getBaseDao (). update ("upload. updatePreUploadInfo ", preUpload); if (Global. BLOCK_UPLOAD_TO! = Global. BLOCK_UPLOAD_TO_LOCAL) {// The block String [] path = preUpload on S2/S3 is deleted after assembly. getS3BlockUrl (); for (String string: path) {try {if (Global. BLOCK_UPLOAD_TO = Global. BLOCK_UPLOAD_TO_S2) {S2Util. deleteFile (preUpload. getBucketUrl (), string);} else {S3Util. deleteFile (preUpload. getBucketUrl (), string) ;}} catch (Exception e) {log. error (e. getMessage (), e) ;}}if (log. isInfoEnabled () log.info (PreUpload. getUuid () + "assembleFileWithBlock");} catch (IOException e) {log. error (e. getMessage (), e); try {if (fileReader! = Null) {fileReader. close ();} if (fileWrite! = Null) {fileWrite. close () ;}} catch (IOException ex) {log. error (e. getMessage (), e) ;}} BlockPreuploadFileInfo is our custom service file processing bean. Okay. The multipart upload server, client source code, and workflow have all been introduced. The above source code has all been practiced by the project, and most of them are still running in some projects. If you are interested, you can modify the above Code to see if the operation is successful. If you have any questions, you can leave a comment in this blog and discuss them together.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.