MultipartEntity实现文件上传的客户端和服务端

客户端:

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {
	private Button uploadBtn;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		uploadBtn = (Button) findViewById(R.id.main_btn);
		uploadBtn.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		if (v == uploadBtn) {
			final List<String> list = new ArrayList<String>();
			list.add("/storage/sdcard0/updateAdtech/orgpic/1.png");
			list.add("/storage/sdcard0/updateAdtech/orgpic/2.png");
			new Thread() {
				public void run() {
					postMethod("just test", "sdcard/image/a.amr", list);
				};
			}.start();
		}
	}

	/**
	 * 
	 * @Description: 上传方法
	 * 
	 * @param audioPath
	 *            上传音频文件地址 例:sdcard/image/a.amr
	 * 
	 * @param text
	 *            上传文本的值
	 * 
	 * @param imageUrlList
	 *            图片地址的集合 例:sdcard/image/a.jpg, sdcard/image/b.jpg
	 * 
	 * @return void
	 */

	private synchronized void postMethod(String text, String audioPath,
			List<String> imageUrlList) {
		try {
			String[] filePath = new String[imageUrlList.size()];
			int size = imageUrlList.size();
			for (int i = 0; i < size; i++) {
				filePath[i] = imageUrlList.get(i);
			}
			// 链接超时,请求超时设置
			BasicHttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams, 10 * 1000);
			HttpConnectionParams.setSoTimeout(httpParams, 10 * 1000);

			// 请求参数设置
			HttpClient client = new DefaultHttpClient(httpParams);
			HttpPost post = new HttpPost(
					"http://service.ireadhome.com/api/Upload/Image");
			MultipartEntity entity = new MultipartEntity();
			// 上传 文本, 转换编码为utf-8 其中"text" 为字段名,
			// 后边new StringBody(text,
			// Charset.forName(CHARSET))为参数值,其实就是正常的值转换成utf-8的编码格式
			entity.addPart("text",
					new StringBody(text, Charset.forName("UTF-8")));
			// 上传多个文本可以在此处添加上边代码,修改字段和值即可

			// 上传音频文件
			entity.addPart("audio",
					new FileBody(new File(audioPath), "audio/*"));
			// 上传图片
			for (String p : filePath) {
				entity.addPart("fileimg", new FileBody(new File(p), "image/*"));
			}
			post.setEntity(entity);
			HttpResponse resp = client.execute(post);
			// 获取回调值
			System.out.println("Response:"
					+ EntityUtils.toString(resp.getEntity()));
			System.out.println("StatusCode:"
					+ resp.getStatusLine().getStatusCode());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

服务端:(SpringBoot)

@RequestMapping("/fileupload")
    public void fileupload(HttpServletRequest request, HttpServletResponse response){

        JSONObject  result = new JSONObject();
        result.put("flag", true);

        String filePath = IniReader.getInstance().getProperty("voicefilePath");

        File path = new File(filePath);
        if(!path.exists())
            path.mkdirs();

        MultipartHttpServletRequest params=((MultipartHttpServletRequest) request);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request)
                .getFiles("file");
        String name=params.getParameter("filename");
        System.out.println("filename:"+name);

        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                    String fileFullPath =filePath+ file.getOriginalFilename();
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(fileFullPath)));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    result.put("flag", true);
                    result.put("errorMsg", "You failed to upload "+file.getOriginalFilename()+" => "+e.getMessage());

                }
            } else {
                result.put("flag", true);
                result.put("errorMsg", "You failed to upload "+" because the file was empty.");
            }
        }

        try {
            response.setContentType("application/octet-stream;");

            ServletOutputStream output = response.getOutputStream();
            output.write(result.toString().getBytes());
            output.flush();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


猜你喜欢

转载自blog.csdn.net/wsh_0703/article/details/80585857
今日推荐