关于使用RESTful api上传文件,基于jax rs接口,不是实现

1. File Uploads with JAX-RS 2: http://blogs.steeplesoft.com/posts/2014/05/01/file-uploads-with-jax-rs-2/

2. Servlet3.0中Servlet的使用:http://haohaoxuexi.iteye.com/blog/2013691

3. 使用curl模拟POST请求上传文件(windows下,linux下“改成‘):curl -X POST -H "Accept: text/plain" -F "name=FORM UPLOAD EXA
MPLE" -F "attachment=@install.xml" http://localhost:9999/RestDeploy/rest/upload


public class Example {
    private String name;
    private byte[] attachment;


    public String getName() {
        return name;
    }


    public void setName(String name) {
        this.name = name;
    }


    public byte[] getAttachment() {
        return attachment;
    }


    public void setAttachment(byte[] attachment) {
        this.attachment = attachment;
    }
}





import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


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


import org.apache.log4j.Logger;


public class MultipartRequestMap extends HashMap<String, List<Object>> {


private static Logger logger = Logger.getLogger(MultipartRequestMap.class);

private static final long serialVersionUID = 1L;
private static final String DEFAULT_ENCODING = "UTF-8";
    private String encoding;
    private String tempLocation;


    public MultipartRequestMap(HttpServletRequest request) {
        this(request, System.getProperty("java.io.tmpdir"));
    }


    public MultipartRequestMap(HttpServletRequest request, String tempLocation) {
        super();
        try {
       
            this.tempLocation = tempLocation;


            this.encoding = request.getCharacterEncoding();
            if (this.encoding == null) {
                try {
                    request.setCharacterEncoding(this.encoding = DEFAULT_ENCODING);
                } catch (UnsupportedEncodingException ex) {
                logger.error(ex);
ex.printStackTrace();
// returnStatus.setReturnCode(e.getErrorCode());
// returnStatus.setReturnMsg(e.getMessage());
// returnStatus.setDetailedMsg(e.getOriginalException()
// .getMessage());
                }
            }


            for (Part part : request.getParts()) {
                String fileName = part.getSubmittedFileName();
                if (fileName == null) {
                    putMulti(part.getName(), getValue(part));
                } else {
                    processFilePart(part, fileName);
                }
            }
        } catch (IOException ex) {
        logger.error(ex);
ex.printStackTrace();
        } catch (ServletException ex1){
        logger.error(ex1);
ex1.printStackTrace();
        }
    }


    public String getStringParameter(String name) {
        List<Object> list = get(name);
        return (list != null) ? (String) get(name).get(0) : null;
    }


    public File getFileParameter(String name) {
        List<Object> list = get(name);
        return (list != null) ? (File) get(name).get(0) : null;
    }


    private void processFilePart(Part part, String fileName) throws IOException {
        File tempFile = new File(tempLocation, fileName);
//        tempFile.createNewFile();
//        tempFile.deleteOnExit();


//        try {
//         BufferedInputStream input = new BufferedInputStream(part.getInputStream(), 8192);
//            BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(tempFile), 8192);
//
//            byte[] buffer = new byte[8192];
//            for (int length = 0; ((length = input.read(buffer)) > 0);) {
//                output.write(buffer, 0, length);
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        part.delete();
        
    String disposition = part.getHeader("content-disposition");  
        System.out.println(disposition);  
        String fileType = part.getContentType();  
        long fileSize = part.getSize();  
        System.out.println("fileName: " + fileName);  
        System.out.println("fileType: " + fileType);  
        System.out.println("fileSize: " + fileSize);  
        System.out.println("uploadPath:" + tempLocation);  
        part.write(tempLocation + File.separator +fileName);  
        /
        putMulti(part.getName(), tempFile);
        part.delete();
    }


    private String getValue(Part part) throws IOException {
        BufferedReader reader
                = new BufferedReader(new InputStreamReader(part.getInputStream(), encoding));
        StringBuilder value = new StringBuilder();
        char[] buffer = new char[8192];
        for (int length; (length = reader.read(buffer)) > 0;) {
            value.append(buffer, 0, length);
        }
        return value.toString();
    }


    private <T> void putMulti(final String key, final T value) {
        List<Object> values = (List<Object>) super.get(key);


        if (values == null) {
            values = new ArrayList();
            values.add(value);
            put(key, values);
        } else {
            values.add(value);
        }
    }
}


@POST
@Path("upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response formPost(@Context HttpServletRequest request) {
        MultipartRequestMap map = new MultipartRequestMap(request);
        Example example = new Example();
        example.setName(map.getStringParameter("name"));
        try {
example.setAttachment(readFile(map.getFileParameter("attachment")));
} catch (IOException e) {
logger.error(e);
e.printStackTrace();
}


        return Response.ok((example.getName() + example.getAttachment().length)).build();
    }

private byte[] readFile(File file) throws IOException{
        long fileSize = file.length();  
        if (fileSize > Integer.MAX_VALUE) {  
            System.out.println("file too big...");  
            return null;  
        }  
        FileInputStream fi = new FileInputStream(file);  
        byte[] buffer = new byte[(int) fileSize];  
        int offset = 0;  
        int numRead = 0;  
        while (offset < buffer.length  
        && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) {  
            offset += numRead;  
        }  
        if (offset != buffer.length) {  
        throw new IOException("Could not completely read file "  
                    + file.getName());  
        }  
        fi.close();  
        return buffer;  
}



web.xml

<servlet>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <load-on-startup>1</load-on-startup>
    <multipart-config>
        <max-file-size>35000000</max-file-size>
        <max-request-size>218018841</max-request-size>
        <file-size-threshold>0</file-size-threshold>
    </multipart-config>
  </servlet>
  <servlet-mapping>
    <servlet-name>javax.ws.rs.core.Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值