public void uploadFilesTest(HttpServletRequest request) throws IOException {
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("C:\\Users\\Administrator\\Desktop\\img.png");
in = fi.openStream();
this.logParamValue("字节长度Content-Length", String.valueOf(fi.openStream().available()));
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);
}
}
}
postman 测试:



本文介绍了一个使用ServletFileUpload处理HTTP请求中的文件上传的方法。通过检查是否为多部分内容,创建ServletFileUpload实例,并设置字符编码为UTF-8。迭代请求中的每一个文件项,获取文件名并将其保存到指定路径。
195

被折叠的 条评论
为什么被折叠?



