【springboot】5、SpingBoot檔案上傳、多檔案上傳、檔案下載(斷點續傳)
阿新 • • 發佈:2018-12-12
檔案上傳
SpringBoot的檔案上傳相對比較簡單,檔案資訊都包含在MultipartFile物件中,只要從中獲取檔案資訊即可 不煽情,直接上程式碼吧,這個部分出門右拐“百度一下”一大堆
/** * 單檔案上傳 * * @param name 攜帶的其他文字表單(可以省略) * @param file 檔案內容 * @return */ @RequestMapping(value = "/upload_single", method = RequestMethod.POST) public @ResponseBody String handleFileUpload(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) { if (!file.isEmpty()) { BufferedOutputStream out = null; try { byte[] bytes = file.getBytes(); out = new BufferedOutputStream( new FileOutputStream(new File(BASE_PATH + "\\" + name + "-" + file.getOriginalFilename()))); out.write(bytes); return "You successfully uploaded " + name + " into " + name + "-uploaded !"; } catch (Exception e) { return "You failed to upload " + name + " => " + e.getMessage(); } finally { if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } else { return "You failed to upload " + name + " because the file was empty."; } }
測試:
<p>單檔案上傳</p> <form method="POST" enctype="multipart/form-data" action="/upload_single"> File to upload: <input type="file" name="file"/><br /> Name: <input type="text" name="name"/> <input type="submit" value="單檔案上傳"/> </form>
多檔案上傳
多檔案上傳需要接收解析出MultipartHttpServletRequest物件中包含的檔案資訊
/** * 多檔案上傳,主要是使用了MultipartHttpServletRequest和MultipartFile * * @param name 攜帶的其他文字表單(可以省略) * @param request * @return */ @RequestMapping(value = "/upload", method = RequestMethod.POST) public @ResponseBody String handleFileUpload(HttpServletRequest request,@RequestParam("name") String name) { List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file"); System.out.println("name==>"+name); MultipartFile file = null; BufferedOutputStream out = null; for (int i = 0; i < files.size(); ++i) { file = files.get(i); if (!file.isEmpty()) { try { byte[] bytes = file.getBytes(); out = new BufferedOutputStream(new FileOutputStream(new File(BASE_PATH + "\\" + file.getOriginalFilename()))); out.write(bytes); } catch (Exception e) { return "failed to upload " + i + " => " + e.getMessage(); } finally { if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } out = null; } } } else { return "failed to upload " + i + " because the file was empty."; } } return "upload successful"; }
測試:
<p>多檔案上傳</p>
<form method="POST" enctype="multipart/form-data"
action="/upload">
Name: <input type="text" name="name"/>
<p>檔案1:<input type="file" name="file" /></p>
<p>檔案2:<input type="file" name="file" /></p>
<p><input type="submit" value="多檔案上傳" /></p>
</form>
檔案下載(斷點續傳)
相對於上傳在檔案下載的處理上,需要自己處理HttpServletResponse中流的返回,這裡直接上一個有斷點續傳的程式碼:
@RequestMapping(value = "/download", method = RequestMethod.GET)
public void getDownload(String name, HttpServletRequest request, HttpServletResponse response) {
// Get your file stream from wherever.
String fullPath = "D:\\upload_test\\" + name;
File downloadFile = new File(fullPath);
ServletContext context = request.getServletContext();
// get MIME type of the file
String mimeType = context.getMimeType(fullPath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
// set content attributes for the response
response.setContentType(mimeType);
// response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
response.setHeader(headerKey, headerValue);
// 解析斷點續傳相關資訊
response.setHeader("Accept-Ranges", "bytes");
long downloadSize = downloadFile.length();
long fromPos = 0, toPos = 0;
if (request.getHeader("Range") == null) {
response.setHeader("Content-Length", downloadSize + "");
} else {
// 若客戶端傳來Range,說明之前下載了一部分,設定206狀態(SC_PARTIAL_CONTENT)
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
String range = request.getHeader("Range");
String bytes = range.replaceAll("bytes=", "");
String[] ary = bytes.split("-");
fromPos = Long.parseLong(ary[0]);
if (ary.length == 2) {
toPos = Long.parseLong(ary[1]);
}
int size;
if (toPos > fromPos) {
size = (int) (toPos - fromPos);
} else {
size = (int) (downloadSize - fromPos);
}
response.setHeader("Content-Length", size + "");
downloadSize = size;
}
// Copy the stream to the response's output stream.
RandomAccessFile in = null;
OutputStream out = null;
try {
in = new RandomAccessFile(downloadFile, "rw");
// 設定下載起始位置
if (fromPos > 0) {
in.seek(fromPos);
}
// 緩衝區大小
int bufLen = (int) (downloadSize < 2048 ? downloadSize : 2048);
byte[] buffer = new byte[bufLen];
int num;
int count = 0; // 當前寫到客戶端的大小
out = response.getOutputStream();
while ((num = in.read(buffer)) != -1) {
out.write(buffer, 0, num);
count += num;
//處理最後一段,計算不滿緩衝區的大小
if (downloadSize - count < bufLen) {
bufLen = (int) (downloadSize-count);
if(bufLen==0){
break;
}
buffer = new byte[bufLen];
}
}
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != in) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
該部分本人直接在Android客戶端上測試: 下載程式碼:
public static boolean downLoadFile(String url, int from, int to,String savePath) {
try {
URL link = new URL(url);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
// 設定斷點續傳的開始位置
if (to != 0) {
conn.setRequestProperty("Range", "bytes=" + from + "-" + to);
}else{
conn.setRequestProperty("Range", "bytes=" + from + "-");
}
Log.e("m_tag", "code:" + conn.getResponseCode());
if (conn.getResponseCode() == 206) {
RandomAccessFile file = new RandomAccessFile(savePath, "rw");
file.seek(from);
InputStream in = conn.getInputStream();
byte[] buffer = new byte[1024];
int num;
while ((num = in.read(buffer)) > 0) {
file.write(buffer, 0, num);
}
file.close();
in.close();
return true;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
Activity中運用:
class MyTask extends AsyncTask<Object, Integer, Object> {
@Override
protected Object doInBackground(Object... params) {
String uri = (String) params[0];
int from = (Integer) params[1];
int to = (Integer) params[2];
String savePath = (String) params[3];
return HttpUtil.downLoadFile(uri, from, to, savePath);
}
@Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
tvRes.setText(result.toString());
}
}
//這裡用兩個按鈕點選模擬分段,第一個按鈕下載0-50B,第二個從50B下載到末尾
...省略其他部分...
case R.id.btn_part_01:
new MyTask().execute("http://192.168.2.183:8080/download?name=11.jpg",0, 50, "/mnt/sdcard/pic_123.jpg");
break;
case R.id.btn_part_02:
new MyTask().execute("http://192.168.2.183:8080/download?name=11.jpg",50, 0, "/mnt/sdcard/pic_123.jpg");
break;
...省略其他部分...
[附]
檔案上傳時相對路徑配置
以上的上傳檔案可以儲存到伺服器端的D:\upload_test但是對於這個路徑,客戶端如果想要使用一個相對路徑來訪問的話,需要做以下配置:
1、在application.properties中宣告一個變數描述該地址
#圖片上傳儲存路徑
imagesPath=file:/D:/upload_test/
2、定義一個配置檔案可以將該絕對路徑對映到一個/images的相對路徑上
package com.example.demo.config;
import org.apache.log4j.spi.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class FileConfig extends WebMvcConfigurerAdapter {
@Value("${imagesPath}")
private String mImagesPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (mImagesPath.equals("") || mImagesPath.equals("${imagesPath}")) {
String imagesPath = FileConfig.class.getClassLoader().getResource("").getPath();
if (imagesPath.indexOf(".jar") > 0) {
imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
} else if (imagesPath.indexOf("classes") > 0) {
imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
}
imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
mImagesPath = imagesPath;
}
System.out.println("imagesPath=" + mImagesPath);
registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
super.addResourceHandlers(registry);
}
}
這樣之後對於伺服器上D:\upload_test\1.jpg這個圖片可以在客戶端直接使用http://127.0.0.1:8080/images/1.jpg這個路徑就可以訪問了