Java 服务端接收多图上传

1 篇文章 0 订阅
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload();

// Parse the request
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
    FileItemStream item = iter.next();
    String name = item.getFieldName();
    InputStream stream = item.openStream();
    if (item.isFormField()) {//表单
        System.out.println("Form field " + name + " with value "
            + Streams.asString(stream) + " detected.");
    } else {//文件
        System.out.println("File field " + name + " with file name "
            + item.getName() + " detected.");
        // Process the input stream
        ...
    }
}
原文链接:http://commons.apache.org/proper/commons-fileupload/streaming.html
 

Demo:

DiskFileItemFactory factory = new DiskFileItemFactory();

ServletFileUpload upload = new ServletFileUpload(factory);

List<FileItem> items = null;

try {

items = upload.parseRequest(req);

} catch (FileUploadException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}   //解析request请求

Iterator<FileItem> iter = items.iterator();

while (iter.hasNext()) {

FileItem item = (FileItem) iter.next();

if (item.isFormField()) { //如果是表单域 ,就是非文件上传元素

// String name = item.getFieldName(); //获取name属性的值

String jsonString;

try {

jsonString = item.getString("UTF-8");

feed = mapper.readValue(jsonString, FeedModel.class);

} catch (UnsupportedEncodingException e1) {

// TODO Auto-generated catch block

e1.printStackTrace();

} catch (JsonParseException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (JsonMappingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

} else {

String fieldName = item.getFieldName(); //文件域中name属性的值

// String fileName = item.getName(); //文件的全路径,绝对路径名加文件名

// String contentType = item.getContentType(); //文件的类型

// long size = item.getSize(); //文件的大小,以字节为单位

File saveFile = new File("/Users/xxxx/Downloads/"+fieldName+".jpg"); //定义一个file指向一个具体的文件

try {

System.out.println(""+fieldName);

item.write(saveFile); //把上传的内容写到一个文件中

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值