本教程示例后台代码以java的web服务来举例说明,采用springMVC框架,后端代码如下:
@RequestMapping("/userPicUpload")
@ResponseBody
public void userPicUpload(HttpServletRequest request){
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
ServletFileUpload upload = new ServletFileUpload();
upload.setHeaderEncoding("UTF-8");
int i = 0;
try {
FileItemIterator iter = upload.getItemIterator(request);
while(iter.hasNext()){
i++;
FileItemStream fi = iter.next();
InputStream in = null;
OutputStream fileout = null;
try {
String fileName = fi.getName();
File file = new File("f:/upload_test/"+ fileName.substring(0, fileName.lastIndexOf(".")) + "_" + i + fileName.substring(fileName.lastIndexOf(".")));
in = fi.openStream();
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
Streams.copy(in, bstream, true);
fileout = new FileOutputStream(file);
bstream.writeTo(fileout);
} catch (IOException e) {
throw new RuntimeException("file copy error!",e);
}finally{
if(in != null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fileout != null){
try {
fileout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
} catch (Exception e) {
throw new RuntimeException("upload file error.",e);
}
}
}