java servlet cos multipart:保存输入流以供以后存储
我正在使用 COS multipart 来处理 servlet 上的文件上传。
处理零件时,我需要使用额外的发布字段(ParamPart)重命名文件,在这种情况下,需要在文件名前面添加“artikelcode”。
因此,我需要将输入流保存在内存中,而不是直接将 FilePart 写入磁盘。
这是我到目前为止的代码:
MultipartParser multipartParser = new MultipartParser(request, 100000000);
String artikelcode = null;
String filename = null;
InputStream in = null;
while ((part = multipartParser.readNextPart()) != null) {
if (part.isFile()) {
FilePart filePart = (FilePart) part;
filename = filePart.getFileName();
//long fileSize = filePart.writeTo(new File(fileSavePath));
if (filename != null) in = filePart.getInputStream();
}
if (part.isParam()) {
ParamPart paramPart = (ParamPart) part;
if (paramPart.getName().equals("artikelcode")) artikelcode = paramPart.getStringValue();
}
}
if (in != null)
{
String fileSavePath = "c:\\upload\\"+artikelcode+"_"+filename;
File file = new File(fileSavePath);
OutputStream out = new FileOutputStream(file);
IOUtils.copy(in, out);
out.close();
}
当文件保存在磁盘上时,它是空的!
感谢您的帮助!!
I am using COS multipart to handle file upload on the servlet.
When processing the parts i need to rename the file with an extra posted field (ParamPart), in this case 'artikelcode' needs to be prepended to the filename.
So instead of directly writing the FilePart to disk i need to save the inputstream in memory.
This is the code i have so far:
MultipartParser multipartParser = new MultipartParser(request, 100000000);
String artikelcode = null;
String filename = null;
InputStream in = null;
while ((part = multipartParser.readNextPart()) != null) {
if (part.isFile()) {
FilePart filePart = (FilePart) part;
filename = filePart.getFileName();
//long fileSize = filePart.writeTo(new File(fileSavePath));
if (filename != null) in = filePart.getInputStream();
}
if (part.isParam()) {
ParamPart paramPart = (ParamPart) part;
if (paramPart.getName().equals("artikelcode")) artikelcode = paramPart.getStringValue();
}
}
if (in != null)
{
String fileSavePath = "c:\\upload\\"+artikelcode+"_"+filename;
File file = new File(fileSavePath);
OutputStream out = new FileOutputStream(file);
IOUtils.copy(in, out);
out.close();
}
When the file is saved on disk, it is empty!
Thanks for your help!!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
调用
readNextPart()
会使您从前一部分获取的任何数据无效。这是一个更好的方法:始终使用临时名称保存文件,然后重命名。
这使您可以轻松地处理许多常见错误,例如:磁盘已满、保存时出错等,因为在 100% 确定新文件完整之前,您永远不会覆盖现有文件。
Calling
readNextPart()
invalidates any data that you got from the previous part.Here is a better approach: Always save the file with a temporary name and then rename it.
This allows you to handle a lot of common errors graciously like: Disk full, errors while saving, etc. because you never overwrite existing files until you are 100% sure the new file is complete.
尝试用单斜杠替换双斜杠,如下所示。
Try to replace double slash with single slash like this..