在java中将图像添加到表单中

时间:2014-09-03 07:17:30

标签: java jsp

我想在JSP中添加具有相同表单的图像和文件。我该怎么办?在这里,我的表格如下:

    <div id="user_img">
                <form name="form1" method="post" enctype="multipart/form-data" action="image_user_upload_db.jsp">
                <input type="file" name="poster" id="imagefile"/>
                <input type="submit" id="submit_img" value="submit"/>
                </form>
            </div>

和帮助保存图像的jsp页面是:

 try{
    String ImageFile="";
    String itemName = "";
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart){
    }
    else{
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try{
            items = upload.parseRequest(request);
        }
        catch (FileUploadException e){
            e.getMessage();
        }

    Iterator itr = items.iterator();
    while (itr.hasNext()){
        FileItem item = (FileItem) itr.next();
        if (item.isFormField()){
            String name = item.getFieldName();
            String value = item.getString();
            if(name.equals("poster")){
                ImageFile=value;
            }
        }
        else{
            try{
                itemName = item.getName();
                File savedFile = new     File(config.getServletContext().getRealPath("/")+"\\img\\user_img\\"+itemName);
                item.write(savedFile);
            }
            catch (Exception e){
                out.println("Error"+e.getMessage());
            }
        }
    }
    try{
        String str="update user_info set img_name='"+itemName+"' where user_id=?";
        PreparedStatement ps=con.prepareStatement(str);
        ps.setInt(1,id1);
        int rs1=ps.executeUpdate();
        response.sendRedirect("profile.jsp");
    }
    catch(Exception el){
        out.println("Inserting error"+el.getMessage());
    }   
}
}

我希望这个表单也采用其他输入类型,但是当我向表单添加另一个输入类型时,它会给出错误。

3 个答案:

答案 0 :(得分:0)

你可以让他们的价值观仔细看看这段代码

if (item.isFormField()){
            String name = item.getFieldName();
            String value = item.getString();
            if(name.equals("poster")){
                ImageFile=value;
            }
 }

获取其他字段值只需使用item.getFieldName()然后检查它是否是您要查找的字段名称,然后将其存储在变量中

String otherField;

if(name.equals("otherField")){

   otherField = item.getString();
}

答案 1 :(得分:0)

在操作页面中使用以下代码

<%

String saveFile="";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
saveFile=config.getServletContext().getRealPath("/")+"user_upload\\"+saveFile;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();

}

%>

此处&#39; user_upload&#39;是一个文件夹名称,将在其中存储上传的文件。

在执行此代码之前,您必须创建一个名为&#39; user_upload&#39;的文件夹。在你的项目目录中。

注意: - 您可以更改文件夹名称。

答案 2 :(得分:0)

use following code




DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(MEMORY_THRESHOLD);
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(MAX_FILE_SIZE);
            upload.setSizeMax(MAX_REQUEST_SIZE); // sets maximum size of request (include file + form data)
            String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;

            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            List<FileItem> formItems = upload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                for (FileItem item : formItems) {
                    if (!item.isFormField()) {
                        String fileName = new File(item.getName()).getName();
                        System.out.println("item.getFieldName() => "+item.getFieldName());
                        String fileAttr[] = fileName.split("\\.");
                        String newFileName = fileAttr[0];
                        int i = 1;
                        while (true) {
                            File f = new File(uploadPath + "\\" + newFileName + "." + fileAttr[1]);
                            if (f.exists()) {
                                newFileName = fileAttr[0] + i;
                                i++;
                            } else {
                                fileName = newFileName + "." + fileAttr[1];
                                break;
                            }
                        }
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        item.write(storeFile);
                        request.setAttribute("message","Upload has been done successfully!");
                    } else {
                        System.out.println("1 item.getFieldName() => "+item.getFieldName());
                        if("description1".equalsIgnoreCase(item.getFieldName())){
                            //this part is for other field except file field
                        }
                    }
                }
            }