基本上我有type="file"
将图像发送到服务器,在服务器中我需要检查图像大小是否不高于1MB,如果它向客户端发送有关图像大小的错误,那么客户端可能会向用户弹出错误。
这是我的servlet脚本:
@MultipartConfig(
maxFileSize=1024*1024 // 1Mb max
)
public class ProPicUploader extends HttpServlet {
private static final long serialVersionUID = 1L;
public void init() throws ServletException
{
System.out.println("Initiate method is called in " + this.getClass().getName());
}
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
MultipartRequest multipartRequest = new MultipartRequest(request, "D:\\");
} catch(IOException e){
out.print("Image size is bigger than 1MB");
System.out.println(e.getMessage());
}
out.print("Successfully Uploaded");
}
public void destroy(){
System.out.println("Destory method is called in: " + this.getClass().getName());
}
}
客户端脚本:
if(formdata){
$.ajax({
url: '../propicuploader',
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function(data){
alert(data);
if(data == "0x00000035"){
$("#NotPictureerror_spn").text("File size is too big, Please select a file upto 2MB");
}
}
error: function(data){
alert(data);
}
});
}
和我的web.xml脚本:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Duck</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ProPicUploader</servlet-name>
<servlet-class>/ProPicUploader</servlet-class>
</servlet>
</web-app>
到目前为止,如果图像大小低于1MB,它会显示Successfully Uploaded
,但如果图像大小高于1MB,它会弹出任何内容,尽管我已经输入了发送错误out.print("Image size is bigger than 1MB")
但我的错误客户永远不会收到它。
如果有人告诉我我做错了什么,我真的很感激。)
答案 0 :(得分:0)
删除此部分
@MultipartConfig(
maxFileSize=1024*1024 // 1Mb max
)
然后重试。 默认情况下,MultipartRequest将上传大小限制为1兆字节