Android Upload File to Server

提交本地文件到服务器,这里仅仅提供一个代码,解释等后期有时间了慢慢写。

客户端代码

class UploadTask extends AsyncTask<String, Integer, String> {

    public UploadTask() {
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        for (int i = 0; i < params.length; i++) {
            String path = params[i];
            HttpURLConnection conn = null;
            DataOutputStream dos = null;
            String lineEnd = "\r\n";
            String twoHyphens = "--";
            String boundary = "******";
            int bytesRead, bytesAvailable, bufferSize;
            byte[] buffer;
            int maxBufferSize = 1* 1024 * 1024;
            File imgFile = new File(path);
            if (!imgFile.isFile()) {
                return null;
            } else {
                try {
                    FileInputStream fis = new FileInputStream(imgFile);
                    URL url = new URL(UPLOAD_URL);
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setDoInput(true);
                    conn.setDoOutput(true);
                    conn.setUseCaches(false);
                    conn.setRequestMethod("POST");
                    conn.setRequestProperty("Connection", "Keep-Alive");
                    conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
                    conn.setRequestProperty("uploaded_file", path);

                    dos = new DataOutputStream(conn.getOutputStream());

                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\'upload_file\';filename=" + path + lineEnd);

                    dos.writeBytes(lineEnd);

                    bytesAvailable = fis.available();

                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    buffer = new byte[bufferSize];

                    bytesRead = fis.read(buffer, 0, bufferSize);
                    while (bytesRead > 0) {
                        dos.write(buffer, 0, bufferSize);

                        bytesAvailable = fis.available();
                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        bytesRead = fis.read(buffer, 0, bufferSize);
                    }

                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                    int responseCode = conn.getResponseCode();

                    String responseMessage = conn.getResponseMessage();
                    if (responseCode == 200) {
                        LogMgr.i(TAG, responseMessage);
                    }
                    fis.close();
                    dos.flush();
                    dos.close();
                } catch (Exception e) {
                    return "error";
                }
            }
        }
        return "Success";
    }

    @Override
    protected void onPostExecute(String result) {
        Log.e(TAG, "[onPostExecute] " + result);
    }

}

服务端代码

@RequestMapping(value = "/upload/report", method = RequestMethod.POST)
public @ResponseBody String uploadReport(@RequestParam String token, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
    request.setCharacterEncoding("utf-8");
    //获得磁盘文件条目工厂。
    DiskFileItemFactory factory = new DiskFileItemFactory();
    //获取文件上传需要保存的路径,upload文件夹需存在。
    //String path = request.getSession().getServletContext().getRealPath("/upload");
    String path = "E://upload";
    //设置暂时存放文件的存储室,这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。
    File storageFile = new File(path);
    if (!storageFile.exists())
        storageFile.mkdirs();
    factory.setRepository(storageFile);
    //设置缓存的大小,当上传文件的容量超过缓存时,就放到暂时存储室。
    factory.setSizeThreshold(1024*1024);
    //上传处理工具类(高水平API上传处理?)
    ServletFileUpload upload = new ServletFileUpload(factory);

    List<FileItem> list = null;
    try{
        //调用 parseRequest(request)方法  获得上传文件 FileItem 的集合list 可实现多文件上传。
        list = (List<FileItem>)upload.parseRequest(request);
        for(FileItem item:list){
            //获取表单属性名字。
            String name = item.getFieldName();
            //如果获取的表单信息是普通的文本信息。即通过页面表单形式传递来的字符串。
            if(item.isFormField()){
                //获取用户具体输入的字符串,
                String value = item.getString();
                request.setAttribute(name, value);
            }
            //如果传入的是非简单字符串,而是图片,音频,视频等二进制文件。
            else{
                String storagePath = receiverFile(request, path, item, name);
                if (storagePath == null || storagePath.length() <= 0) {
                    response.getWriter().write("文件上传失败");
                } else {
                    //reportDao.insert(1, storagePath, "123456", 456789876);
                }
            }
        }
    }catch(Exception e){
        e.printStackTrace();
        return "upload field.";
    } finally {
        if (list != null) {
            for (FileItem item:list)
                item.delete();
        }
    }
    return "upload success";
}

/**
* @param request
* @param path
* @param item
* @param name
* @return
*/
private String receiverFile(HttpServletRequest request, String path, FileItem item, String name) {
OutputStream out = null;
InputStream in = null;
try {
//获取路径名
String value = item.getName();
//取到最后一个反斜杠。
int start = value.lastIndexOf(“/”);
//截取上传文件的 字符串名字。+1是去掉反斜杠。
String filename = value.substring(start+1);
request.setAttribute(name, filename);

        //第三方提供的方法直接写到文件中
        //item.write(new File(path,filename));

        //创建文件,用于接收流中的字节流
        File tempFile = new File(path, filename);
        //创建文件输出流,将客户端的文件输出至零时文件中
        out = new FileOutputStream(tempFile);
        in = item.getInputStream();

        int length;
        byte[] buf = new byte[1024];
        System.out.println("获取文件总量的容量:"+ item.getSize());

        while((length = in.read(buf))!=-1){
            out.write(buf,0,length);
        }
        in.close();
        out.close();

        //返回接收的文件存储路径
        return tempFile.getAbsolutePath();
    } catch (Exception e) {
        return "";
    } finally {
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/wxpqqa/article/details/64124193