Android上傳單文件和多文件(后臺(tái)使用MultipartFile)

android代碼:

package heath.com.microchat.utils;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
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.ContentBody;
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.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

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

import heath.com.microchat.service.ServiceRulesException;

public class UploadServerUtils {

    public static String uploadLogFile(String uploadUrl, String filePath, String folderPath) {
        String result = null;
        try {
            HttpClient hc = new DefaultHttpClient();
            hc.getParams().setParameter(
                    CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpPost hp = new HttpPost(uploadUrl);
            File file = new File(filePath);
            final MultipartEntity entity = new MultipartEntity();
            ContentBody contentBody = new FileBody(file);
            entity.addPart("file", contentBody);
            entity.addPart("folderPath", new StringBody(folderPath, Charset.forName("UTF-8")));
            hp.setEntity(entity);
            HttpResponse hr = hc.execute(hp);
            HttpEntity he = hr.getEntity();
            int statusCode = hr.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK)
                throw new ServiceRulesException(Common.MSG_SERVER_ERROR);

            result = EntityUtils.toString(he, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("TAG", "文件上傳失敗眉枕!上傳文件為:" + filePath);
            Log.e("TAG", "報(bào)錯(cuò)信息toString:" + e.toString());
        }
        return result;
    }

    public static String uploadLogFiles(String uploadUrl, List<String> filePaths, String folderPath) {
        String result = null;
        try {
            HttpClient hc = new DefaultHttpClient();
            hc.getParams().setParameter(
                    CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            HttpPost hp = new HttpPost(uploadUrl);
            final MultipartEntity entity = new MultipartEntity();
            for (String filePath:filePaths){
                File file = new File(filePath);
                ContentBody contentBody = new FileBody(file);
                entity.addPart("files", contentBody);
            }
            entity.addPart("folderPath", new StringBody(folderPath, Charset.forName("UTF-8")));
            hp.setEntity(entity);
            HttpResponse hr = hc.execute(hp);
            HttpEntity he = hr.getEntity();
            int statusCode = hr.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK)
                throw new ServiceRulesException(Common.MSG_SERVER_ERROR);
            result = EntityUtils.toString(he, HTTP.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("TAG", "文件上傳失敗拌牲!上傳文件為:" + filePaths.toString());
            Log.e("TAG", "報(bào)錯(cuò)信息toString:" + e.toString());
        }
        return result;
    }

}

后臺(tái)代碼及環(huán)境:

環(huán)境:tomcat8.5及以上贵试,需要commons-fileupload-1.3.1.jar、commons-io-2.4.jar兩個(gè)jar包攀操;

本上傳使用SSM框架院仿,所以在springmvc.xml文件配置:

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <property name="maxUploadSize" value="102400000"></property>
    </bean>

后臺(tái)代碼:

本上傳示例,本人使用的是前端傳入上傳路勁速和,不在后臺(tái)定死路勁歹垫。

package org.heath.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.heath.utils.RandomCode;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import net.sf.json.JSONArray;

@Controller
@RequestMapping("upload")
@ResponseBody
public class UploadController {

    @RequestMapping("fileUpload.action")
    private String fileUpload(HttpServletRequest request, @RequestParam("file") MultipartFile file, @RequestParam("folderPath") String folderPath) throws IOException {
        String fileName = "error";
        try {
            fileName = file.getOriginalFilename();
            fileName = "MicroChat_" + RandomCode.getRandomCode() + "_" + fileName;
            folderPath = request.getServletContext().getRealPath(folderPath);
            InputStream input = file.getInputStream();
            File folder = new File(folderPath);
            judeDirExists(folder);
            OutputStream outputStream = new FileOutputStream(
                    folderPath + File.separator + fileName);
            byte[] b = new byte[1024];
            while ((input.read(b)) != -1) {
                outputStream.write(b);
            }
            input.close();
            outputStream.close();
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
    }

    @RequestMapping("filesUpload.action")
    private Map<String, Object> filesUpload(HttpServletRequest request, @RequestParam("files") MultipartFile[] files, @RequestParam("folderPath") String folderPath) throws IOException {
        JSONArray fileNames = new JSONArray();
        Map<String, Object> returnMap = new HashMap<String, Object>();
        folderPath = request.getServletContext().getRealPath(folderPath);
        try {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getOriginalFilename();
                fileName = "MicroChat_" + RandomCode.getRandomCode() + "_" + fileName;
                InputStream input = files[i].getInputStream();
                File folder = new File(folderPath);
                judeDirExists(folder);
                OutputStream outputStream = new FileOutputStream(
                        folderPath + File.separator + fileName);
                byte[] b = new byte[1024];
                while ((input.read(b)) != -1) {
                    outputStream.write(b);
                }
                input.close();
                outputStream.close();
                fileNames.add(fileName);
            }
            returnMap.put("code", "200");
            returnMap.put("msg", "success");
            returnMap.put("fileNames", fileNames);
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
            returnMap.put("code", "414");
            returnMap.put("msg", "error");
            return returnMap;
        }
    }

    // 判斷文件夾是否存在
    public static void judeDirExists(File file) {

        if (file.exists()) {
            if (file.isDirectory()) {
                System.out.println("dir exists");
            } else {
                System.out.println("the same name file exists, can not create dir");
            }
        } else {
            System.out.println("dir not exists, create it ...");
            file.mkdir();
        }

    }

}

文件及jar下載地址:https://download.csdn.net/download/qq_32090185/10930145

有不懂的地方,可以留言颠放,我看到會(huì)進(jìn)行回復(fù)排惨。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市碰凶,隨后出現(xiàn)的幾起案子暮芭,更是在濱河造成了極大的恐慌,老刑警劉巖欲低,帶你破解...
    沈念sama閱讀 212,542評(píng)論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件辕宏,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡砾莱,警方通過查閱死者的電腦和手機(jī)瑞筐,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來恤磷,“玉大人面哼,你說我怎么就攤上這事干奢『斓” “怎么了捆等?”我有些...
    開封第一講書人閱讀 158,021評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)河胎。 經(jīng)常有香客問我,道長(zhǎng)虎敦,這世上最難降的妖魔是什么游岳? 我笑而不...
    開封第一講書人閱讀 56,682評(píng)論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮其徙,結(jié)果婚禮上胚迫,老公的妹妹穿的比我還像新娘。我一直安慰自己唾那,他們只是感情好访锻,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,792評(píng)論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般期犬。 火紅的嫁衣襯著肌膚如雪河哑。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,985評(píng)論 1 291
  • 那天龟虎,我揣著相機(jī)與錄音璃谨,去河邊找鬼。 笑死鲤妥,一個(gè)胖子當(dāng)著我的面吹牛佳吞,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播棉安,決...
    沈念sama閱讀 39,107評(píng)論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼容达,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了垂券?” 一聲冷哼從身側(cè)響起花盐,我...
    開封第一講書人閱讀 37,845評(píng)論 0 268
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎菇爪,沒想到半個(gè)月后算芯,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,299評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡凳宙,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,612評(píng)論 2 327
  • 正文 我和宋清朗相戀三年熙揍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片氏涩。...
    茶點(diǎn)故事閱讀 38,747評(píng)論 1 341
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡届囚,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出是尖,到底是詐尸還是另有隱情意系,我是刑警寧澤,帶...
    沈念sama閱讀 34,441評(píng)論 4 333
  • 正文 年R本政府宣布饺汹,位于F島的核電站蛔添,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏兜辞。R本人自食惡果不足惜迎瞧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 40,072評(píng)論 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望逸吵。 院中可真熱鬧凶硅,春花似錦、人聲如沸扫皱。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至编检,卻和暖如春胎食,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背允懂。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評(píng)論 1 267
  • 我被黑心中介騙來泰國(guó)打工厕怜, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人蕾总。 一個(gè)月前我還...
    沈念sama閱讀 46,545評(píng)論 2 362
  • 正文 我出身青樓粥航,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親生百。 傳聞我的和親對(duì)象是個(gè)殘疾皇子递雀,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,658評(píng)論 2 350

推薦閱讀更多精彩內(nèi)容