上传文件并将其存储到文件夹中?

时间:2012-04-08 02:18:01

标签: java jsp

我正在尝试对我的应用程序进行编程以上传图像,然后将它们存储在一个文件夹中。它会打印出文件的详细信息,但不会将其存储到文件夹中。我正在关注用户指南和答案,我仍然不知道我做错了什么?

import java.io.File;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadAvatarCommand implements Command {

    @Override
    public String execute(HttpServletRequest request,
            HttpServletResponse response) {

        DiskFileItemFactory factory = new DiskFileItemFactory();
        String contextRoot = request.getServletContext().getRealPath("/");
        factory.setRepository(new File(contextRoot + "WEB-INF/tmp"));
        ServletFileUpload upload = new ServletFileUpload(factory);

        try {
            List<FileItem> items = upload.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                    // Process form file field (input type="file").
                    System.out.println("Field name: " + item.getFieldName());
                    System.out.println("File name: " + item.getName());
                    System.out.println("File size: " + item.getSize());
                    System.out.println("File type: " + item.getContentType());

                    String fileName = item.getName();
                    try {
                        File saveFile = new File(fileName);
                        saveFile.createNewFile();
                        item.write(saveFile);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileUploadException e) {
            try {
                throw new ServletException("Cannot parse multipart request.", e);
            } catch (ServletException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

        return "profile";
    }

}

1 个答案:

答案 0 :(得分:1)

如果您没有任何错误,那么这段代码:

File saveFile = new File(fileName);
saveFile.createNewFile();
item.write(saveFile);

在当前文件夹中创建一个名为fileName的新文件(只是一个简单的名称,如“file.txt”)。

如果您想知道当前的工作文件夹是哪个,请尝试打印:

System.out.println("Current folder: " + (new File(".")).getCanonicalPath())

所以你可以检查文件是否在这里。

然后,如果您想将文件放在您想要的文件夹上,您可以使用:

File saveFile = new File("/my/upload/folder",fileName);

并将“/ my / upload / folder”替换为您喜欢的文件夹的路径。