我对JAVA很新。我试图通过Java servlet和netbeans中的Ajax保存图像。在netbeans我试过相同的编码与tomcat服务器工作正常。如果我使用Glashfish它是扔错误。以下是我的编码。
的Servlet
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Part img = request.getPart("img");
String id = (String) request.getParameter("ids");
out.println(saveImage(img, "E:\\Users\\XXXX\\Desktop\\wine_shop\\build\\web\\images\\wines"));
}
保存图片方式:
private String saveImage(Part img, String path) throws IOException {
File fileSaveDir = new File(path);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdirs();
}
System.out.println("Upload File Directory=" + fileSaveDir.getAbsolutePath());
String fileName = null;
fileName = extractFileName(img);
img.write(path+ fileName);
return "1";
}
我的错误:
java.io.FileNotFoundException: E:\Users\xxxx\AppData\Roaming\NetBeans\8.2\config\GF_4.1.1\domain1\generated\jsp\wine_shop\E:\Users\xxxx\Desktop\wine_shop\build\web\images\winesth.jpg (The filename, directory name, or volume label syntax is incorrect)
帮助解决这个问题..
答案 0 :(得分:0)
尝试此代码。
@WebServlet(name = "abc", urlPatterns = {"/upload"})
@MultipartConfig
public class abc extends HttpServlet {
private final static Logger LOGGER =
Logger.getLogger(abc.class.getCanonicalName());
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
final String path = "E:\\shopping\\web\\admin\\img";
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("<br/> ERROR: " + fne.getMessage());
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}