Java - file upload problem [duplicate]
Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
public class Apply extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
InputStreamReader input = new InputStreamReader(request.getInputStream());
BufferedReader buffer = new BufferedReader(input);
String line="";
line=buffer.readLine();
开发者_运维知识库System.out.println("Multipart data " + line );
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart)
{
// upload file
}
else
{
// failed, no input
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
}
JSP.
<form enctype="multipart/form-data" method="post" action="apply">
<fieldset>
<br/>
<legend>Upload</legend>
<br/>
<label>Select file to upload</label>
<input type="file" name="file" /><br />
<br/>
<a href="apply" class="jUiButton">Submit</a>
</fieldset>
</form>
<script>$(".jUiButton").button()</script>
The boolean and input always validates as false/null and I can't figure why. Following this guide: http://sacharya.com/file-upload/
in the web-inf/lib - we have commons-fileupload-1.2.2.jar and commons-io-2.0.1.jar.
Any ideas?
You're not actually submitting the form. You're navigating to the page with a GET
request.
Replace your "Submit" anchor with a submit button:
<button type="submit" class="jUiButton">Submit</button>
You could keep the <a>
but then you would have to use JavaScript to submit the form manually.
You should not read the HttpServletRequest#getInputStream()
beforehand. It can be read only once. The Commons FileUpload cannot read it anymore if you have read it yourself beforehand. Get rid of all those lines in your servlet until ServletFileUpload#isMultipartContent()
line.
The guide you are following is out of date (2008). If this is a new project you might want to start with an annotation based approach. This guide might be better to follow (2010). A file upload controller would then look like:
@Controller
public class FileUploadContoller {
@RequestMapping(value = "/fileupload", method = RequestMethod.POST)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public String ingest(@RequestParam("file") final MultipartFile file) throws Exception {
if (file.isEmpty()) {
System.out.println("empty");
} else {
System.out.println("not empty");
}
// do something with file.getBytes()
return("ok");
}
}
This is only the controller and you will need to add the appropriate Spring configuration. I could help further if you want to go down this route.
精彩评论