我想插入一个文件但总是失败并显示“Exception - > null”。我应该在代码中更改什么才能正常运行?
@WebServlet(name="ServletFileUpload", urlPatterns={"/ServletFileUpload"}) // specify urlPattern for servlet
@MultipartConfig(location="C:\\Users\\Hitesh\\Documents\\NetBeansProjects\\MajorProject\\build\\web") // specifies servlet takes multipart/form-data
public class ServletFileUpload extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// get access to file that is uploaded from client
Part p1 = request.getPart("file");
InputStream is = p1.getInputStream();
// read filename which is sent as a part
Part p2 = request.getPart("photoname");
Scanner s = new Scanner(p2.getInputStream());
String filename = s.nextLine(); // read filename from stream
// get filename to use on the server
String outputfile = this.getServletContext().getRealPath(filename); // get path on the server
FileOutputStream os = new FileOutputStream (outputfile);
// write bytes taken from uploaded file to target file
int ch = is.read();
while (ch != -1) {
os.write(ch);
ch = is.read();
}
os.close();
out.println("<h3>File uploaded successfully!</h3>");
}
catch(Exception ex) {
out.println("Exception -->" + ex.getMessage());
}
finally {
out.close();
}
}
}