[英]Image file is corrupted after uploading using servlet
我正在嘗試使用下面的 servlet 上傳圖像但是上傳后我可以保存文件但我無法打開我檢查了文件已損壞。
我沒有使用注釋,而是在 web.xml 中描述了 multipart-config。 在這段代碼中,我試圖獲取使用 AJAX 發送數據的圖像文件。 然后我被重定向到注冊 servlet,我正在使用 InputStream class 來處理數據。 在此之后,我創建文件並將此 Inputdata 上傳到服務器上某個目錄中的文件。
public class Register extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException{
String username=req.getParameter("username");
String password=req.getParameter("password");
String email=req.getParameter("email");
Part part = req.getPart("image");
String filename = part.getSubmittedFileName();
InputStream is = req.getInputStream();
byte[] data = new byte[is.available()];
String path = "D:\\FullstackWeb\\images\\icon\\"+filename;
System.out.println(path);
FileOutputStream fos=new FileOutputStream(path);
fos.write(data);
res.setContentType("text/html");
PrintWriter out = res.getWriter();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://dns1.nishchay.com:3306/register","demouser","123Nbr@");
String query = "Insert INTO register.signup(username,email,userpassword,filename) values(? ,?, ?,?)";
PreparedStatement pstmt= conn.prepareStatement(query);
pstmt.setString(1, username);
pstmt.setString(2, email);
pstmt.setString(3, password);
pstmt.setString(4, path);
pstmt.executeUpdate();
conn.close();
}catch(Exception e) {
out.println("<h1>Issue is occured</h1>");
}
}
}```
您沒有讀取圖像數據:
InputStream is = req.getInputStream();
byte[] data = new byte[is.available()];
String path = "D:\\FullstackWeb\\images\\icon\\"+filename;
System.out.println(path);
FileOutputStream fos=new FileOutputStream(path);
fos.write(data);
不包含任何is.read()
調用,也不會關閉FileOutputStream
。
除此之外,您分配的緩沖區對於大多數圖像來說都很小。 InputStream.available()
狀態的 JavaDoc
返回可以從此輸入 stream 無阻塞地讀取(或跳過)的字節數的估計值
要完全讀取圖像數據,您只需將上面的代碼替換為
Files.copy(is, Paths.get("D:\\FullstackWeb\\images\\icon\\"+filename));
但有一個很大的警告:由於文件名是由您的服務用戶提供的,這會使您的代碼面臨安全問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.