If you need to upload a large file, you should consider the following logic:
To upload a large file, you generally need to upload the file in slices (chunks), and then upload all Slices are merged into a complete file. It can be implemented according to the following logic:
The front-end selects the file to be uploaded on the page and uses the Blob.slice method to slice the file. Generally, the size of each slice is a fixed value (such as 5MB) and record how many slices there are in total.
Upload the slices to the backend service separately, and you can use libraries such as XMLHttpRequest or Axios to send Ajax requests. For each slice, three parameters need to be included: current slice index (starting from 0), total number of slices, and slice file data.
After the backend service receives the slice, it saves it to a temporary file under the specified path, and records the uploaded slice index and upload status. If a slice fails to be uploaded, the front end is notified to retransmit the slice.
When all slices are uploaded successfully, the backend service reads the contents of all slices and merges them into a complete file. File merging can be achieved using java.io.SequenceInputStream and BufferedOutputStream.
Finally, return the response result of successful file upload to the front end.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
|
controller layer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
|
Among them, file.upload-path is the save file upload The path can be configured in application.properties or application.yml. At the same time, you need to add the Bean of RedisTemplate to record the upload status.
If you need to use RedisTemplate, you need to introduce the following package
1 2 3 4 |
|
At the same time configure the redis information in yml
1 2 3 |
|
Then in your own class When used like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
Notes
It is necessary to control the size of the slices uploaded each time to take into account the upload speed and stability, and avoid occupying too many server resources or being affected by the network. The upload failed due to instability.
There is a sequence for uploading slices. You need to ensure that all slices are uploaded before merging. Otherwise, incomplete files or file merge errors may occur.
After the upload is completed, temporary files need to be cleaned up in time to avoid server crashes caused by taking up too much disk space. You can set up a periodic task to clean up expired temporary files.
The above is the detailed content of How to use vue+springboot to upload large files. For more information, please follow other related articles on the PHP Chinese website!