1. 程式人生 > >Retrofit 2.0 單檔案、多檔案上傳

Retrofit 2.0 單檔案、多檔案上傳

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("有檔案提交");
// 設定response的編碼格式
response.setHeader("Content-type", "text/html;charset=UTF-8");
response.setCharacterEncoding("utf-8");


// 建立檔案專案工廠物件
DiskFileItemFactory factory = new DiskFileItemFactory();


// 設定檔案上傳路徑
// String upload = this.getServletContext().getRealPath("/");
String upload = "D:/aa/image/";

// 獲取系統預設的臨時檔案儲存路徑,該路徑為Tomcat根目錄下的temp資料夾
String temp = System.getProperty("java.io.tmpdir");
// 設定緩衝區大小為 5M
factory.setSizeThreshold(1024 * 1024 * 5);
// 設定臨時資料夾為temp
factory.setRepository(new File(temp));
// 用工廠例項化上傳元件,ServletFileUpload 用來解析檔案上傳請求
ServletFileUpload servletFileUpload = new ServletFileUpload(factory);


// 解析結果放在List中
try {
List<FileItem> list = servletFileUpload.parseRequest(request);


for (FileItem item : list) {
String name = item.getFieldName();
InputStream is = item.getInputStream();


System.out.println("the current name is " + name);


if (name.contains("aFile")) {
try {
inputStream2File(is, upload + "\\" + /*
* System.
* currentTimeMillis
* () +
*/item.getName());
} catch (Exception e) {
e.printStackTrace();
}
} else {
String key = item.getName();
String value = item.getString();
System.out.println(key + "---" + value);
}
}


// out.write("success");
Gson gson = new Gson();
ResponseData data = new ResponseData<String>(200, "成功", "上傳了檔案");
String gsonStr = gson.toJson(data);


System.out.println("響應資料::" + gsonStr);
response.getWriter().print(gsonStr);
} catch (FileUploadException e) {
e.printStackTrace();
System.out.println("failure");
}
PrintWriter out = response.getWriter();
out.flush();
out.close();
}


// 流轉化成字串
public static String inputStream2String(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.toString();
}


// 流轉化成檔案
public static void inputStream2File(InputStream is, String savePath)
throws Exception {
System.out.println("the file path is  :" + savePath);
File file = new File(savePath);
InputStream inputSteam = is;
BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
int f;
while ((f = fis.read()) != -1) {
fos.write(f);
}
fos.flush();
fos.close();
fis.close();
inputSteam.close();


}