用作備忘,
代碼如下:
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject upload1(MultipartFormDataInput formDataInput) {
JSONObject json = new JSONObject();
Integer isSuccess = Constants.INTEGER_ZERO;
FileOutputStream fop = null;
InputStream inputStream = null;
try {
//送出的form表單
Map<String, List<InputPart>> uploadForm = formDataInput.getFormDataMap();
// //如果有中文參數的話,用下面方法防止亂碼
// //中文表單資料
// InputPart zhongweninputParts = uploadForm.get("title").get(0);
// //解決中文亂碼
// zhongweninputParts.setMediaType(MediaType.TEXT_PLAIN_TYPE);
//圖檔
InputPart imgfileInputParts = uploadForm.get("imgfile").get(0);
inputStream = imgfileInputParts.getBody(InputStream.class, null);
String img = "D:\\" + System.currentTimeMillis() + ".png";
byte[] bytes = IOUtils.toByteArray(inputStream);
fop = new FileOutputStream(img);
fop.write(bytes);
json.put("img", img);
} catch (Exception e) {
json.put("isSuccess", Constants.INTEGER_ZERO.toString());
logger.info("上傳圖檔出錯");
logger.info(e);
} finally {
try {
fop.flush();
fop.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
json.put("isSuccess", isSuccess.toString());
}
return json;
}