关闭

文件上传 传输

391人阅读 评论(0) 收藏 举报
分类:
<div>
<input class="in_device_version" type="file" style="display: none"/>
<div class="write_only" style="margin-top: 10px">
<button class="m_button" style="width: 108px">版本升级</button>
        <span class="device_rslt" style="margin-left: 10px"></span>
</div>

</div>


var isVersionUploading;
function initVersionUpload($p,type){
    var $inp= $p.find(".in_device_version"),
        $r=$p.find(".device_rslt");
    function beforeSend(formData, jqForm, options){
    isVersionUploading=true;
        $r.html("开始上传" );
        console.log("开始上传");
    }
    var opts={
        url: controlServer+"/upload_attach",
        beforeSend: beforeSend,
        done: function (e, data) {
            if (data.result.success) {
                $r.html("文件:" + data.result.data.name+" 上传成功,正在升级.....");
                 upgradeVersion($(".device").find(".strl"),data.result.data,1,$r);                
            } else {
                $r.html("上传失败:" + data.result.err);
            }
        },
        progressall: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10);
            $r.html(progress);
        },
        fail: function (e, data) {
            $r.html("上传失败:" + data.errorThrown);
        },       
    };
    $inp.fileupload(opts);
}

function upgradeVersion($multi,data,type,$el){
      url=urlBase+"device/upgrade/" + id+ "/" + number+ "/" + type;
    var beforeSend = function (formData, jqForm, options) {
    }
    var comp= function (jqXHR, textStatus) {
    }
    var doSuc = function (data, textStatus, jqXHR) {
        setTimeout(function () {
        isVersionUploading=false;
            if(data.success){
            //完成后的处理
            $el.html("升级成功.");
            }else{
            //失败后处理
            $el.html("升级详情.");
            addErrorBtn($el,data.err);
            }
        }, 500);
    };
    var err = function (jqXHR, textStatus, errorThrown) {
        $el.html("升级失败."+errorThrown);
    }
    var options = {
        data:JSON.stringify(data),
        beforeSend: beforeSend,
        success: doSuc,
        complete:comp,
        error: err,
        dataType: "json",
        contentType: 'application/json',
        type: 'POST'
    };
    $.ajax(url, options);
}


@RequestMapping(value={"/upload_attach"},method=RequestMethod.POST)
public @ResponseBody Result upAttach(HttpServletRequest request, HttpServletResponse response)
{
try {
return Result.build(uploadService.uploadAttach(  request, response, context));
} catch (Exception e) {
e.printStackTrace();
return Result.build(e);
}
}


public class uploadService {

public DeviceVersion uploadAttach(HttpServletRequest request, HttpServletResponse response,ServletContext context) throws Exception{
if(!ServletFileUpload.isMultipartContent(request)){
throw new Exception("请求无效");
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context));
ServletFileUpload up = new ServletFileUpload(factory);
// FileItemIterator itemIterator=up.getItemIterator(request);
List<FileItem> items = up.parseRequest(request);
FileItem targetItem=null;
for (FileItem item : items) {
if (!item.isFormField()) {
targetItem=item;
break;
}
}
if(targetItem==null)throw new Exception("请求无效");
//文件保存目录路径
String fName=targetItem.getName();
String contextPath=context.getRealPath("/");
if (!contextPath.endsWith(File.separator))contextPath += File.separator;
String savePath =contextPath+"doc"+File.separator+"deviceversion"+File.separator;
File dir=new File(savePath);
if(!dir.exists())dir.mkdirs();
//文件保存目录URL
File f=new File(savePath, fName);
targetItem.write(f);
return new DeviceVersion(f.length(),savePath,fName);
}

}


---------------------------------------------------------------------------------------------------------------------

public String uploadDeviceVersion(HttpServletRequest request, HttpServletResponse response,ServletContext context) throws Exception{
if(!ServletFileUpload.isMultipartContent(request)){
throw new Exception("请求无效");
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setFileCleaningTracker(FileCleanerCleanup.getFileCleaningTracker(context));
ServletFileUpload up = new ServletFileUpload(factory);
List<FileItem> items = up.parseRequest(request);
FileItem targetItem=null;
for (FileItem item : items) {
if (!item.isFormField()) {
System.out.println("AppService testField:"+item.getFieldName()+";length:"+item.get().length);
targetItem=item;
break;
}
}
return uploadFile(targetItem);
}


//每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
    private static final String BOUNDARY ="---------1asdfasfda 32r asdff";
   
/*
* 将本地的图片上传到图片服务器,并返回文件的标识
* 此处模拟web端的请求,调用文件服务器的上传文件服务。
*  
*/
private String uploadFile(FileItem item) throws Exception
{
// 向服务器发送post请求
String serverUrl = mcConfig.getUploadDeviceVersion();
URL url = new URL(serverUrl);
System.out.println(serverUrl);
        HttpURLConnection connection= (HttpURLConnection) url.openConnection();
       
        // 发送POST请求必须设置如下两行
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Connection","Keep-Alive");
        connection.setRequestProperty("Charset","UTF-8");
        connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);
       
        String boundary = BOUNDARY;
        StringBuffer contentBody = new StringBuffer("--" + BOUNDARY);
        String endBoundary ="\r\n--" + boundary + "--\r\n";
       
        OutputStream out =connection.getOutputStream();

        String boundaryMessage1 =contentBody.toString();
        out.write(boundaryMessage1.getBytes("UTF-8"));
        
        contentBody = new StringBuffer();
        contentBody.append("\r\n")
               .append("Content-Disposition:form-data; name=\"")
               .append("upload1" +"\"; ")   // form中field的名称               
               .append("filename=\"")
               .append(item.getName() +"\"")   //上传文件的文件名
               .append("\r\n")
               .append("Content-Type:application/octet-stream")
               .append("\r\n\r\n");
                
         String boundaryMessage2 = contentBody.toString();
         out.write(boundaryMessage2.getBytes("UTF-8"));
        
         DataInputStream dis= new DataInputStream(item.getInputStream());
         int bytes = 0;
         byte[] bufferOut = new byte[(int) item.get().length];
         bytes = dis.read(bufferOut);
         out.write(bufferOut,0, bytes);
         dis.close();
         contentBody = new StringBuffer();
         contentBody.append("------------HV2ymHFg03ehbqgZCaKO6jyH");
        
         String boundaryMessage = contentBody.toString();
         out.write(boundaryMessage.getBytes("utf-8"));
        out.write("------------HV2ymHFg03ehbqgZCaKO6jyH--\r\n".getBytes("UTF-8"));
       
        // 3. 写结尾
        out.write(endBoundary.getBytes("UTF-8"));
        out.flush();
        out.close();
       
        // 4. 从服务器获得回答的内容
        String strLine="";
        String strResponse ="";
       
        InputStream in =connection.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        while((strLine =reader.readLine()) != null)
        {
        strResponse +=strLine +"\n";
        }
       
        JSONObject ret = JSON.parseObject(strResponse);
        if(ret == null)
        throw new Exception("上传时异常失败!");
        if(!ret.getBooleanValue("success"))
        {
//         String error = ret.getString("err");
        throw new Exception("上传失败!");
        }
        String filename = ret.getString("data"); 
        if(StringUtils.isEmpty(filename))
        throw new Exception("上传失败!返回格式不正确。");
        return filename;
}



@RequestMapping(value="/file/deviceVersion",method= {RequestMethod.POST, RequestMethod.GET})
public @ResponseBody Result downloadVersion(HttpServletRequest req, HttpServletResponse res)
{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
if (!ServletFileUpload.isMultipartContent(req)) {
return Result.build(101, "提交数据格式不正确,无法处理!");
}
List<FileItem> list = null;
try {
list = upload.parseRequest(req);
} catch (FileUploadException e1) {
logger.error(e1.getMessage());
return Result.build(101, "文件接收失败!" + e1.getMessage());
}
if (list == null || list.size() == 0) {
return Result.build(102, "未接收到传入的文件,无法处理!");
}
try {
for (FileItem item : list) {
if (!item.isFormField()) {
String savePath  = req.getSession().getServletContext().getRealPath(File.separator)+item.getName();
File f=new File(savePath);
item.write(f);
return Result.build(item.getName());
}
}
} catch (Throwable e) {
return Result.build(e);
} finally {
}
return Result.build(102, "未接收到传入的文件,无法处理!");
}





0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:69153次
    • 积分:1591
    • 等级:
    • 排名:千里之外
    • 原创:85篇
    • 转载:14篇
    • 译文:0篇
    • 评论:0条