开发者社区 问答 正文

关于java上传图片文件的问题

前台用的是backbone的框架,现在有一个添加商品的功能,里面要添加图片,最后点击添加,将其他字段与文件一起保存,怎么实现?

展开
收起
蛮大人123 2016-06-08 16:24:12 2426 分享 版权
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    在struts2中实现(以图片上传为例)
    1.FileUpload.jsp代码清单如下:
    screenshot
    3.FileUploadAction.java的代码清单如下 :

    public class FileUploadAction extends ActionSupport{
    private static final long serialVersionUID = 572146812454l ;
    private static final int BUFFER_SIZE = 16 * 1024 ;
    //注意,文件上传时<s:file/>同时与myFile,myFileContentType,myFileFileName绑定
    //所以同时要提供myFileContentType,myFileFileName的set方法
    private File myFile; //上传文件
    private String contentType;//上传文件类型
    private String fileName; //上传文件名
    private String imageFileName;
    private String caption;//文件说明,与页面属性绑定
    public void setMyFileContentType(String contentType) {
    System.out.println("文件类型 : " + contentType);
    this .contentType = contentType;
    }
    public void setMyFileFileName(String fileName) {
    System.out.println("文件名称 : " + fileName);
    this .fileName = fileName;
    }
    public void setMyFile(File myFile) {
    this .myFile = myFile;
    }
    public String getImageFileName() {
    return imageFileName;
    }
    public String getCaption() {
    return caption;
    }
    public void setCaption(String caption) {
    this .caption = caption;
    }
    private static void copy(File src, File dst) {
    try {
    InputStream in = null ;
    OutputStream out = null ;
    try {
    in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
    out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
    byte [] buffer = new byte [BUFFER_SIZE];
    while (in.read(buffer) > 0 ) {
    out.write(buffer);
    }
    } finally {
    if ( null != in) {
    in.close();
    }
    if ( null != out) {
    out.close();
    }
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    private static String getExtention(String fileName) {
    int pos = fileName.lastIndexOf(".");
    return fileName.substring(pos);
    }
    @Override
    public String execute() {
    imageFileName = new Date().getTime() + getExtention(fileName);
    File imageFile = new File(ServletActionContext.getServletContext().getRealPath("UploadImages" ) + "/" + imageFileName);
    copy(myFile, imageFile);
    return SUCCESS;
    }
    }

    注:此时仅为方便实现Action所以继承ActionSupport,并Overrider execute()方法
    在struts2中任何一个POJO都可以作为Action
    4.struts.xml清单如下:
    screenshot
    5.web.xml清单如下:
    screenshot

    2019-07-17 19:32:15
    赞同 展开评论
问答分类:
问答地址: