我已经完成了部分成功的文件上传。扩展名为-.html,.jpeg,.pdf等的文件工作正常。当涉及.zip,.rpm,.tar.gz它不起作用。文件正在转移到所需的路径,但文件已损坏。
<tr>
<td>FileName</td>
<td><input type="text" name="filename" size="30"/></td>
</tr>
<tr>
<td>Select main category</td>
<td>
<select name="main">
<option >--Select--</option>
<option>aerospace</option>
<option>automotive</option>
<option>energy</option>
<option>icengines</option>
<option>wind</option>
<option>turbo</option>
<option>it</option>
<option>training</option>
</select>
</td>
</tr>
<tr>
<td>Select sub category</td>
<td>
<select name="sub">
<option >--Select--</option>
<option>internal</option>
<option>demo</option>
<option>best practice</option>
<option>marketing</option>
<option>papers & public</option>
<option>validation</option>
<option>training</option>
</select>
</td>
</tr>
<tr>
<td>Upload File</td>
<td><input type="file" name="file1"/></td>
</tr>
它将获取文件名以及下拉值和type =“file”,文件被转移到所需的路径,但文件已损坏上述格式(我已经检查过这些格式)。我需要所有要存储的文件不会被破坏。
我的servlet:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
private String filename="";
private String main1="";
private String location;
private String sub;
private File uploadFile;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = fileUpload.parseRequest(request);
Iterator ir = items.iterator();
while(ir.hasNext()){
FileItem item = (FileItem)ir.next();
if(item.isFormField())
{
String name = item.getFieldName();
if(name != null)
{
if(name.equals("userName"))
{
filename = item.getString();
}
else if(name.equals("main"))
{
main1 = item.getString();
}
else if(name.equals("sub"))
{
sub=item.getString();
}
}
}else{
location = File.separator+"home"+File.separator+"adapco"+File.separator+"Desktop"+ File.separator +"output"+ File.separator +main1+File.separator+sub+File.separator+filename;
uploadFile = new File(location);
long size = item.getSize();
if(size <= 1024*1024*1024)
{
item.write(uploadFile);
out.println("Your File is uploaded successfully ");
}else{
out.println("Your File is not uploaded.File size should be less than 1gb");
}
}
}
} catch (Exception e) {
}
}
}