我从doPost请求获取getInputStream问题并在之前设置文件名。它给了我一个文件名正确但空文件为0kB的文件。如果我评论设置fileName而不是我将获得非空文件。
我的流程:从Android应用程序我将PDF文件存档到上传服务器,如http POST。在服务器上,doPost就像下面的方法。
如何设置文件名并获取非空文件?
function getDetail(){
$.get("folder/selectfile2.php?opt1="+$("#id1").val()+"&opt2="+$("#id2").val(), function(data){
$("#data_detail").html(data);
});
}
编辑:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = null;
//Get all the parts from request and write it to the file on server
//getFileName return filename
for (Part part : request.getParts()) {
fileName = getFileName(part);
}
File saveFile = new File(SAVE_DIR + fileName);
// opens input stream of the request for reading data
InputStream inputStream = request.getInputStream();
// opens an output stream for writing file
FileOutputStream outputStream = new FileOutputStream(saveFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
// sends response to client
response.getWriter().print("UPLOAD DONE");
}
解决方案:
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
System.out.println("content-disposition header= " + contentDisp);
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length() - 1);
}
}
return "";
}
答案 0 :(得分:3)
while (not end of file)
{
while (not end of line)
{
while (next char isn't /)
{
temporary string x += char
}
foo.push_back(string) //ID
while (next char isn't /)
{
string bar += char //value
}
}
}
提供了Part
方法,因此在处理零件时应使用该方法代替getInputStream()
。
然而... 的
Part.write()是一种将此上传项目写入磁盘的便捷方法,因此您只需使用request.getInputStream();
即可为您处理(注意part.write(SAVE_DIR + part.getSubmittedFileName());
仅适用于Servlet 3.1 )。
答案 1 :(得分:0)
在执行outputstream.close()
之前执行outputstream.flush()